panFormatter static method

List<TextInputFormatter> panFormatter()

panFormatter formats input as a PAN number (e.g., XXXXX9999X).

Implementation

static List<TextInputFormatter> panFormatter() {
  return [
    TextInputFormatter.withFunction((oldValue, newValue) {
      String newText = newValue.text.toUpperCase();
      if (newText.length > 10) {
        newText = newText.substring(0, 10);
      }
      final StringBuffer buffer = StringBuffer();
      for (int i = 0; i < newText.length; i++) {
        if (i < 5) {
          // First 5 characters should be alphabets
          if (RegExp(r'[A-Z]').hasMatch(newText[i])) {
            buffer.write(newText[i]);
          } else {
            break;
          }
        } else if (i < 9) {
          // Next 4 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),
      );
    }),
  ];
}