voterIdFormatter static method

List<TextInputFormatter> voterIdFormatter()

voterIdFormatter formats input as a voter ID (e.g., ABCD1234567).

Implementation

static List<TextInputFormatter> voterIdFormatter() {
  return [
    TextInputFormatter.withFunction((oldValue, newValue) {
      String newText =
          newValue.text.toUpperCase().replaceAll(RegExp(r'\s+\b|\b\s'), '');
      if (newText.length > 10) {
        newText = newText.substring(0, 10);
      }
      final StringBuffer buffer = StringBuffer();
      for (int i = 0; i < newText.length; i++) {
        if (i < 3) {
          // First 3 characters should be alphabets
          if (RegExp(r'[A-Z]').hasMatch(newText[i])) {
            buffer.write(newText[i]);
          } else {
            break;
          }
        } else if (i < 9) {
          // Next 6 characters should be digits
          if (RegExp(r'\d').hasMatch(newText[i])) {
            buffer.write(newText[i]);
          } else {
            break;
          }
        } else {
          // Last character should be an alphabet
          if (RegExp(r'[A-Z]').hasMatch(newText[i])) {
            buffer.write(newText[i]);
          } else {
            break;
          }
        }
      }
      final String formattedText = buffer.toString();
      return TextEditingValue(
        text: formattedText,
        selection: TextSelection.collapsed(offset: formattedText.length),
      );
    }),
  ];
}