Last active
August 2, 2023 18:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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