zipCodeFormatter static method

List<TextInputFormatter> zipCodeFormatter()

zipCodeFormatter formats input as a ZIP code (e.g., XXXXX or XXXXX-XXXX).

Implementation

static List<TextInputFormatter> zipCodeFormatter() {
  return [
    TextInputFormatter.withFunction((oldValue, newValue) {
      String newText = newValue.text.replaceAll(RegExp(r'\D'), '');
      if (newText.length > 9) {
        newText = newText.substring(0, 9);
      }
      final StringBuffer buffer = StringBuffer();
      for (int i = 0; i < newText.length; i++) {
        buffer.write(newText[i]);
        if (i == 4 && newText.length > 5) {
          buffer.write(
              '-'); // Add hyphen after first 5 digits if more digits exist
        }
      }
      final String formattedText = buffer.toString();
      return TextEditingValue(
        text: formattedText,
        selection: TextSelection.collapsed(offset: formattedText.length),
      );
    }),
  ];
}