date method
use to validate date fields
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) => Mask.validations.date(
value,
error: 'your message error', // optional field
min: DateTime('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?.length != 10) {
return error;
} else {
bool validate = true;
final dateString = value!.replaceAll(RegExp('[^0-9]'), '');
if (dateString.length == 8) {
DateTime date = DateTime.parse(dateString);
final values = value.split('/');
validate = validate && values[2] == '${date.year}'.padLeft(4, '0');
validate = validate && values[1] == '${date.month}'.padLeft(2, '0');
validate = validate && values[0] == '${date.day}'.padLeft(2, '0');
bool rangeMin = (min?.compareTo(date) ?? -2) >= 0;
bool rangeMax = (max?.compareTo(date) ?? 2) <= 0;
if (!validate || rangeMax || rangeMin) return error;
} else {
return error;
}
}
return null;
}