Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict Special Character Input Flutter

Tags:

flutter

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.

like image 941
SupremeAbraxas Avatar asked May 21 '18 05:05

SupremeAbraxas


People also ask

How do you validate only letters in flutter?

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.

How do you restrict Emojis on flutter?

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.


2 Answers

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
),
like image 182
Siddy Hacks Avatar answered Oct 21 '22 12:10

Siddy Hacks


WhitelistingTextInputFormatter is deprecated. You should use FilteringTextInputFormatter.allow:

inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]")), ]

or FilteringTextInputFormatter.deny instead of BlacklistingTextInputFormatter

like image 44
Eduardo Avatar answered Oct 21 '22 13:10

Eduardo