Home > OS >  How to Restricting user input in text field flutter?
How to Restricting user input in text field flutter?

Time:09-23

I have a text field where I want to limit the user input for a range. e.g. I want the first number is zero the second number is three or four . How can I achieve this in the text field? I can't find any argument to set this.

my code

TextFormField(
                         textAlign: TextAlign.center,
                         enableSuggestions: false,
                         autocorrect: false,
                         maxLength: 12,
                        inputFormatters: [ FilteringTextInputFormatter.digitsOnly],
                         keyboardType: TextInputType.number)

** Addition : i add this instruction but not working , what is the problem now

FilteringTextInputFormatter.deny(RegExp(r'^(?:[0][3-4])?[0-9]{12}$')),

CodePudding user response:

You can do this with a mask or changing the onChanged value.

Try:

onChanged: (value) => {
  int n = int.parse(value)??0;
  int oldN = int.parse(myController.text.substring(0,1))??0;

  switch(oldN){
    case 0:
       if (n != 2 || n != 3){
         myController.text =  myController.text.substring(0,myCobtroller.lenght-1);
       }
  }
}

In this example, If First number is 0 and next number is different of 2 or 3 the controller don't be changed.

...

Edit I Create a complete example for you here: https://gist.github.com/sergiotucano/7738517c264b672da7ea6a15e676d231

CodePudding user response:

This will be working fine:

TextFormField(
                             textAlign: TextAlign.center,
                             enableSuggestions: false,
                             autocorrect: false,
                             maxLength: 12,
                            inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("^0[34][0-9]*$")),],
                             keyboardType: TextInputType.number)
  • Related