formatEditUpdate method

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

  // Get the previous and current input strings
  String pText = oldValue.text;
  String cText = newValue.text;
  // Abbreviate lengths
  int cLen = cText.length;
  int pLen = pText.length;

  if (cLen == 1) {
    // Can only be 0, 1, 2 or 3
    if (int.parse(cText) > 3) {
      // Remove char
      cText = '0$cText/';
    }
  } else if (cLen == 2 && pLen == 1) {
    // Days cannot be greater than 31
    int dd = int.parse(cText.substring(0, 2));
    if (dd == 0 || dd > 31) {
      // Remove char
      cText = cText.substring(0, 1);
    } else {
      // Add a / char
      cText += '/';
    }
  } else if (cLen == 4) {
    // Can only be 0 or 1
    if (int.parse(cText.substring(3, 4)) > 1) {
      // Remove char
      cText = '${cText.substring(0, 3)}0${cText.substring(3, 4)}/';
    }
  } else if (cLen == 5 && pLen == 4) {
    // Month cannot be greater than 12
    int mm = int.parse(cText.substring(3, 5));
    if (mm == 0 || mm > 12) {
      // Remove char
      cText = cText.substring(0, 4);
    } else {
      // Add a / char
      cText += '/';
    }
  } else if ((cLen == 3 && pLen == 4) || (cLen == 6 && pLen == 7)) {
    // 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)}/';
    } else {
      // Insert / char
      cText = '${cText.substring(0, pLen)}/${cText.substring(pLen, pLen + 1)}';
    }
  } else if (cLen == 6 && pLen == 5) {
    // Can only be 1 or 2 - if so insert a / char
    int y1 = int.parse(cText.substring(5, 6));
    if (y1 < 1 || y1 > 2) {
      // Replace char
      cText = '${cText.substring(0, 5)}/';
    } else {
      // Insert / char
      cText = '${cText.substring(0, 5)}/${cText.substring(5, 6)}';
    }
  } else if (cLen == 7) {
    // Can only be 1 or 2
    int y1 = int.parse(cText.substring(6, 7));
    if (y1 < 1 || y1 > 2) {
      // Remove char
      cText = cText.substring(0, 6);
    }
  } else if (cLen == 8) {
    // Can only be 19 or 10
    int y2 = int.parse(cText.substring(6, 8));
    if (y2 < 19 || y2 > 10) {
      // Remove char
      cText = cText.substring(0, 7);
    }
  }

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