ifscFormatter static method

List<TextInputFormatter> ifscFormatter()

ifscFormatter formats input as an IFSC code (e.g., ABCD0123456).

Implementation

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