fluttertext-formattingtextformfieldflutter-textformfield

Restrict leading zero in TextFormField in Flutter


Currently, I'm looking at a TextFormField restriction.

My requirement is

  1. Allow single 0 in TextFormField
  2. If it is 099, I want to remove the leading 0. So, it's 99
  3. Do not allow symbols or special characters like "?" or "."

I have tried the below code, but it's still allowed to input "?" or "."

inputFormatters: [
    new FilteringTextInputFormatter.allow(new RegExp("[0-9.]")),
    new FilteringTextInputFormatter.deny(RegExp(r'^0+(?=.)')),
],

I am seeking your help on this.

Thanks in advance!


Solution

  • you can create a text controller at first :

    TextEditingController textEditingController = TextEditingController();
    

    then you can apply this text field :

    TextFormField(
            keyboardType: TextInputType.number,
            controller: textEditingController,
            onChanged: (val){
              if(val.characters.characterAt(0) == Characters("0") && val.length > 1){
                // we need to remove the first char
                textEditingController.text = val.substring(1);
                // we need to move the cursor
                textEditingController.selection = TextSelection.collapsed(offset: textEditingController.text.length);
              }
            },
          )
    

    like this you will be able to enter a single zero but you will not be able write 099 it will be converted automatically to 99 .