isAge function

bool isAge(
  1. String? value, {
  2. int? minAge,
  3. int? maxAge,
})

Returns true if the value is a valid age.

If minAge and/or maxAge are provided, the parsed age must fall within that range. If both are omitted, the value only needs to be a non-negative whole number.

Implementation

bool isAge(String? value, {int? minAge, int? maxAge}) {
  if (value == null || value.trim().isEmpty) return false;

  if (minAge != null) {
    assert(minAge >= 0, 'minAge must be 0 or greater');
  }
  if (maxAge != null) {
    assert(maxAge >= 0, 'maxAge must be 0 or greater');
  }
  if (minAge != null && maxAge != null) {
    assert(
      minAge <= maxAge,
      'minAge ($minAge) cannot be greater than maxAge ($maxAge)',
    );
  }

  final age = int.tryParse(value.trim());
  if (age == null || age < 0) return false;

  if (minAge != null && age < minAge) return false;
  if (maxAge != null && age > maxAge) return false;
  return true;
}