formatEditUpdate method

  1. @override
TextEditingValue formatEditUpdate(
  1. TextEditingValue prevText,
  2. TextEditingValue currText
)
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 prevText, TextEditingValue currText) {
  int selectionIndex;

  String pText = prevText.text;
  String cText = currText.text;
  int cLen = cText.length;
  int pLen = pText.length;

  if (cLen == 1) {
    // Can only be 0, 1
    if (int.parse(cText) > 1) {
      // Remove char
      cText = '';
    }
  } else if (cLen == 2 && pLen == 1) {
    // Month cannot be greater than 12
    int dd = int.parse(cText.substring(0, 2));
    if (dd == 0 || dd > 12) {
      // Remove char
      cText = cText.substring(0, 1);
    } else {
      // Add a / char
      cText += '/';
    }
  } else if (cLen == 4) {
    // Can only be 2
    if (int.parse(cText.substring(3, 4)) < 2) {
      // Remove char
      cText = cText.substring(0, 3);
    }
  } else if (cLen == 5 && pLen == 4) {
    // Year cannot be greater than 21
    int mm = int.parse(cText.substring(3, 5));
    if (mm == 0 || mm < 21) {
      // Remove char
      cText = cText.substring(0, 4);
    } else {
      // Add a / char
      cText += '';
    }
  } else if ((cLen == 3 && pLen == 4)) {
    // Remove / char
    cText = cText.substring(0, cText.length - 1);
  } else if (cLen == 3 && pLen == 2) {
    if (int.parse(cText.substring(2, 3)) > 1) {
      // Replace char
      cText = cText.substring(0, 2) + '/' + cText.substring(2, 3);
    } else {
      // Insert / char
      cText = cText.substring(0, pLen);
    }
  }

  selectionIndex = cText.length;
  return TextEditingValue(
      text: cText,
      selection: TextSelection.collapsed(offset: selectionIndex));
}