dateTime method
use to validate dateTime fields
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) => Mask.validations.dateTime(
value,
error: 'your message error', // optional field
min: DateTime.parse('1999-01-01 08:00'), // optional field
max: DateTime.parse('1999-01-01 18:00'), // optional field
timeWithSeconds: false, // optional field
),
),
------------ or ------------
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: Mask.validations.dateTime,
),
Implementation
String? dateTime(
String? value, {
String error = 'Data inválida',
DateTime? min,
DateTime? max,
bool timeWithSeconds = false,
}) {
final values = (value ?? "").split(' ');
if (values.length != 2) return error;
final dateSTR = values[0];
final timeSTR = values[1];
if (dateSTR.trim().length != 10) return error;
if (timeWithSeconds) {
if (timeSTR.trim().length != 8) return error;
} else {
if (timeSTR.trim().length != 5) return error;
}
final time = DateTime.tryParse('0000-00-00 $timeSTR');
if (time == null) return error;
final str = dateSTR.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 = dateSTR.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 ${time.hour}:${time.minute}:${time.second}');
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;
}