formatEditUpdate method
- TextEditingValue oldValue,
- TextEditingValue newValue
override
Called when text is being typed or cut/copy/pasted in the EditableText.
You can override the resulting text based on the previous text value and the incoming new text value.
When formatters are chained, oldValue reflects the initial value of
TextEditingValue at the beginning of the chain.
Implementation
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
String text = newValue.text;
// If anything was deleted.
if (text.length + 1 == oldValue.text.length) {
if (!text.endsWith('-') && oldValue.text.endsWith('-')) {
text = text.substring(0, text.length - 1);
}
}
// Remove anything that's not a digit
text = text.replaceAll(RegExp(r'[^0-9]'), '');
// Enforce max length of 8 digits (dd + mm + yyyy).
if (text.length > 8) {
text = text.substring(0, 8);
}
// Validate the proper date digits.
if (text.isNotEmpty) {
final String dayPart0 = text.substring(0, 1);
final int day0 = int.tryParse(dayPart0) ?? 0;
// First "day" digit is only `0-3`.
if (day0 > 3) {
return oldValue;
}
if (text.length >= 2) {
final String dayPart1 = text.substring(1, 2);
final int day1 = int.tryParse(dayPart1) ?? 0;
// Second "day" digit is only `0-1` when first one is `3`.
if (day0 == 3 && day1 > 1) {
return oldValue;
}
// Second "day" digit cannot be `0` when first one is `0`.
if (day0 == 0 && day1 == 0) {
return oldValue;
}
if (text.length >= 3) {
final String monthPart1 = text.substring(2, 3);
final int month1 = int.tryParse(monthPart1) ?? 0;
// First "month" digit can only be 0 or 1.
if (month1 > 1) {
return oldValue;
}
if (text.length >= 4) {
final String monthPart2 = text.substring(3, 4);
final int month2 = int.tryParse(monthPart2) ?? 0;
// Second "month" digit can only be `0-2` when first one is `1`.
if (month1 == 1 && month2 > 2) {
return oldValue;
}
}
}
}
}
// Auto-insert separators.
final StringBuffer buffer = StringBuffer();
for (int i = 0; i < text.length; i++) {
buffer.write(text[i]);
if (i == 1 || i == 3) {
buffer.write('-');
}
}
final String newText = buffer.toString();
return TextEditingValue(
text: newText,
selection: TextSelection.collapsed(offset: newText.length),
);
}