I have a TextField that will only take numbers as an input. The Keyboard that appears allows for the input of the the following characters: "-(hyphen) ,(comma) .(period) and space". How can I prevent the user from entering all except the period.
child: new TextField(
controller: _controller,
maxLengthEnforced: true,
keyboardType: TextInputType.number,
maxLength: 4, //9999 upper limit
), //TextField
I've tried to use RegExp to take the _controller text, remove the characters and place it back into to field without any luck.
...//Add Listener to _controller
_controller.addListener(restrictCharacters);
...
//Listener
void restrictCharacters(){
RegExp regexp = new RegExp(
r"^|\-|\,|\ ",
caseSensitive: false,
multiLine: false,);
String text = _controller.text;
String chng = text.replaceaLL(regExp,"");
_controller.text = chng;
}
When applied the cursor moves to beginning and the field keeps the - (hyphen) for example.
Define the valid characters // alphanumeric static final validCharacters = RegExp(r'^[a-zA-Z0-9]+$'); The regex above matches upper and lowercase letters and numbers. If you need other characters you can add them.
It should be something like this RegExp("[A-Za-z0-9#+-.]* ") just put all the special characters you want inside the [ ]. This regexp indicates allow characters mentioned in the brackets and * at the end means 0 or more times.
In your TextInputField() include this paramenter
inputFormatters: [new WhitelistingTextInputFormatter(RegExp("[0-9]")),],
If you want to allow only letters the the Regex would be
inputFormatters: [new WhitelistingTextInputFormatter(RegExp("[a-zA-Z]")),],
Update WhitelistingTextInputFormatter has been deprecated
use FilteringTextInputFormatter like this:
TextField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("[0-9a-zA-Z]")),
], // Only numbers can be entered
),
WhitelistingTextInputFormatter
is deprecated. You should use FilteringTextInputFormatter.allow
:
inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]")), ]
or FilteringTextInputFormatter.deny
instead of BlacklistingTextInputFormatter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With