Want to add a mask in a TextField in Flutter? This solution checks when date is out of range (eg. there is not month like 13). It’s super inefficient, but it works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class DateFormatter extends TextInputFormatter { final String mask = 'xx-xx-xxxx'; final String separator = '-'; @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { if(newValue.text.length > 0) { if(newValue.text.length > oldValue.text.length) { String lastEnteredChar = newValue.text.substring(newValue.text.length-1); if(!_isNumeric(lastEnteredChar)) return oldValue; if(newValue.text.length > mask.length) return oldValue; if(newValue.text.length < mask.length && mask[newValue.text.length - 1] == separator) { String value = _validateValue(oldValue.text); print(value); return TextEditingValue( text: '$value$separator$lastEnteredChar', selection: TextSelection.collapsed( offset: newValue.selection.end + 1, ), ); } if(newValue.text.length == mask.length) { return TextEditingValue( text: '${_validateValue(newValue.text)}', selection: TextSelection.collapsed( offset: newValue.selection.end, ), ); } } } return newValue; } bool _isNumeric(String s) { if(s == null) return false; return double.parse(s, (e) => null) != null; } String _validateValue(String s) { String result = s; if (s.length < 4) { // days int num = int.parse(s.substring(s.length-2)); String raw = s.substring(0, s.length-2); if (num == 0) { result = raw + '01'; } else if (num > 31) { result = raw + '31'; } else { result = s; } } else if (s.length < 7) { // month int num = int.parse(s.substring(s.length-2)); String raw = s.substring(0, s.length-2); if (num == 0) { result = raw + '01'; } else if (num > 12) { result = raw + '12'; } else { result = s; } } else { // year int num = int.parse(s.substring(s.length-4)); String raw = s.substring(0, s.length-4); if (num < 1950) { result = raw + '1950'; } else if (num > 2006) { result = raw + '2006'; } else { result = s; } } print(result); return result; } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.