gstFormatter static method
gstFormatter formats input as a GST number (e.g., 22AAAAA0000A1Z5).
Implementation
static List<TextInputFormatter> gstFormatter() {
return [
TextInputFormatter.withFunction((oldValue, newValue) {
String newText = newValue.text.toUpperCase();
if (newText.length > 15) {
newText = newText.substring(0, 15);
}
final StringBuffer buffer = StringBuffer();
for (int i = 0; i < newText.length; i++) {
if (i < 2) {
// First 2 characters should be digits
if (RegExp(r'\d').hasMatch(newText[i])) {
buffer.write(newText[i]);
} else {
break;
}
} else if (i < 12) {
// Next 10 characters should be alphabets or digits
if (RegExp(r'[A-Z0-9]').hasMatch(newText[i])) {
buffer.write(newText[i]);
} else {
break;
}
} else if (i == 12) {
// 13th character should be an alphabet
if (RegExp(r'[A-Z]').hasMatch(newText[i])) {
buffer.write(newText[i]);
} else {
break;
}
} else if (i == 13) {
// 14th character should be a digit
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),
);
}),
];
}