date method

String? date(
  1. String? value, {
  2. String error = 'Data inválida',
  3. DateTime? min,
  4. DateTime? max,
})

use to validate date fields

TextFormField(
  autovalidateMode: AutovalidateMode.onUserInteraction,
  validator: (value) => Mask.validations.date(
    value,
    error: 'your message error', // optional field
    min: DateTime.parse('1999-01-01'), // optional field
    max: DateTime.now(), // optional field
  ),
),

------------ or ------------

TextFormField(
  autovalidateMode: AutovalidateMode.onUserInteraction,
  validator: Mask.validations.date,
),

Implementation

String? date(
  String? value, {
  String error = 'Data inválida',
  DateTime? min,
  DateTime? max,
}) {
  if (value?.trim().length != 10) return error;

  final str = value!.replaceAll(RegExp(r'[0-9]'), '');
  if (str.length != 2) return error;
  if (str[0] != str[1]) return error;
  if (str[0] != '/' && str[0] != '-') return error;

  final special = str[0];
  final dateInt = value.split(special).map(int.parse).toList();

  final year = '${mat.max(dateInt[0], dateInt[2])}'.padLeft(4, '0');
  final month = '${dateInt[1]}'.padLeft(2, '0');
  final day = '${mat.min(dateInt[0], dateInt[2])}'.padLeft(2, '0');

  final date = DateTime.tryParse('$year$month$day');
  if (date == null) return error;

  final rangeMin = (min?.compareTo(date) ?? -2) >= 0;
  final rangeMax = (max?.compareTo(date) ?? 2) <= 0;
  if (rangeMax && max != null) return error;
  if (rangeMin && min != null) return error;

  return null;
}