Skip to content

Instantly share code, notes, and snippets.

@Meghatronics
Created May 1, 2023 20:25
Show Gist options
  • Select an option

  • Save Meghatronics/c75df5253fc865f087c214d0a95bfd90 to your computer and use it in GitHub Desktop.

Select an option

Save Meghatronics/c75df5253fc865f087c214d0a95bfd90 to your computer and use it in GitHub Desktop.
Date Field input formatter and validator with example
import 'package:flutter/services.dart';
class DateInputFormatter extends TextInputFormatter {
final String separator;
static const _maxLength = 8;
DateInputFormatter({required this.separator});
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
// Remove any non-numeric characters from the new value
String sanitizedValue = newValue.text.replaceAll(RegExp('[^0-9]'), '');
// If the sanitized value is longer than the max length, truncate it
if (sanitizedValue.length > _maxLength) {
sanitizedValue = sanitizedValue.substring(0, _maxLength);
}
// Add dashes to the sanitized value at the appropriate positions
String formattedValue = '';
for (int i = 0; i < sanitizedValue.length; i++) {
if (i == 2 || i == 4) {
formattedValue += separator;
}
formattedValue += sanitizedValue[i];
}
// If the new value is the same as the formatted value, no need to update the text editing value
if (newValue.text == formattedValue) {
return newValue;
}
// Otherwise, create and return a new text editing value with the formatted value
return TextEditingValue(
text: formattedValue,
selection: TextSelection.collapsed(offset: formattedValue.length),
);
}
}
TextFormField(
controller: idVerificationVm.dobField,
inputFormatters: [DateInputFormatter(separator: '/')],
validator: (dob) => validateDate(
dob,
'/',
1900,
DateTime.now().year - 18,
),
keyboardType: TextInputType.number,
),
mixin ValidatorMixin {
String? validateDate(
String? date, String separator, int? earliestYear, int? latestYear) {
if (date == null || date.trim().isEmpty) {
return 'Date of Birth is required';
}
final components = date.split(separator);
if (components.length != 3) {
return 'Enter a valid date';
}
final month = int.tryParse(components[1]);
final day = int.tryParse(components[0]);
final year = int.tryParse(components[2]);
if (month == null || month > 12 || month < 1) {
return 'Date month cannot be ${components[1]}';
}
if (year == null) {
return 'Provide a valid year for this date';
}
if (earliestYear != null && year < earliestYear) {
return 'Year cannot be earlier than $earliestYear';
}
if (latestYear != null && year > latestYear) {
return 'Year cannot be after $latestYear';
}
final days = DateUtils.getDaysInMonth(year, month);
if (day == null || day > days || day < 1) {
return 'Date day cannot be ${components[0]}';
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment