Skip to content

Instantly share code, notes, and snippets.

@dubemezeagwu
Last active August 2, 2023 18:42
Show Gist options
  • Save dubemezeagwu/e0130f9886f168fb450c375cfed49733 to your computer and use it in GitHub Desktop.
Save dubemezeagwu/e0130f9886f168fb450c375cfed49733 to your computer and use it in GitHub Desktop.
Card Number InputFormatter - format payment card inputs automatically for month and card numbers
class CardMonthInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
var newText = newValue.text;
if (newValue.selection.baseOffset == 0) {
return newValue;
}
var buffer = StringBuffer();
for (int i = 0; i < newText.length; i++) {
buffer.write(newText[i]);
var nonZeroIndex = i + 1;
if (nonZeroIndex % 2 == 0 && nonZeroIndex != newText.length) {
buffer.write('/');
}
}
var string = buffer.toString();
return newValue.copyWith(
text: string,
selection: TextSelection.collapsed(offset: string.length));
}
}
@dubemezeagwu
class CardNumberInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
var newText = newValue.text;
if (newValue.selection.baseOffset == 0) {
return newValue;
}
var buffer = StringBuffer();
for (int i = 0; i < newText.length; i++) {
buffer.write(newText[i]);
var nonZeroIndex = i + 1;
if (nonZeroIndex % 4 == 0 && nonZeroIndex != newText.length) {
buffer.write(" "); // Single space
}
}
var string = buffer.toString();
return newValue.copyWith(
text: string,
selection: TextSelection.collapsed(offset: string.length));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment