timeInputValidator static method

String? timeInputValidator(
  1. String? input
)

Validates time input format and values

Checks if the input represents a valid time in 24-hour format.

Validation Rules:

  • Must contain 3-4 digits (e.g., "930" or "1030")
  • Hours must be 00-23
  • Minutes must be 00-59

Examples:

  • "1030" → null (valid)
  • "2530" → "Invalid time" (25 hours)
  • "1070" → "Invalid time" (70 minutes)
  • "12" → "format: HrMn" (too short)

input - Input string to validate Returns null if valid, error message if invalid

Implementation

static String? timeInputValidator(String? input) {
  if (input == null || input.isEmpty) {
    return 'Empty';
  }

  // Remove all non digits characters
  input = _removeNonDigits(input);

  if (input.length < 3 || input.length > 4) {
    return 'HHMM';
  }

  int hours;
  int minutes;

  if (input.length == 3) {
    // For 3 digits: intelligently choose between HH:M0 and 0H:MM formats
    final hoursAsHHM = int.parse(input.substring(0, 2));
    final minutesAs0HMM = int.parse(input.substring(1, 3));

    if (hoursAsHHM <= 23) {
      // Valid hour when treating as HH:M0 format
      hours = hoursAsHHM;
      minutes = int.parse(input[2]) * 10;
    } else if (hoursAsHHM <= 29) {
      // Hours 24-29: wrap and use HH:M0 format
      hours = hoursAsHHM % 24;
      minutes = int.parse(input[2]) * 10;
    } else if (minutesAs0HMM <= 59) {
      // Hours >= 30 with valid minutes: use 0H:MM format
      hours = int.parse(input[0]);
      minutes = minutesAs0HMM;
    } else {
      // Hours >= 30 AND minutes > 59: wrap hours and use HH:M0
      hours = hoursAsHHM % 24;
      minutes = int.parse(input[2]) * 10;
    }
  } else {
    // For 4 digits: standard HH:MM format with hour wrapping
    hours = int.parse(input.substring(0, 2));
    if (hours > 23) {
      hours = hours % 24;
    }
    minutes = int.parse(input.substring(2, 4));
  }

  if (hours > 23 || minutes > 59) {
    return 'Invalid time';
  }
  return null;
}