vandet
vandet

Reputation: 39

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!

Upvotes: 2

Views: 2597

Answers (3)

Robert Apikyan
Robert Apikyan

Reputation: 2127

Here is the way to do the same with TextInputFormatters

List<TextInputFormatter> onlyUnsignedNumbers() {
  final disallowZero = FilteringTextInputFormatter.deny(
    RegExp(r'^0+'),
  );
  return [
    FilteringTextInputFormatter(RegExp("[0-9]"), allow: true),
    TextInputFormatter.withFunction(
        (TextEditingValue oldValue, TextEditingValue newValue) {
      final newValueText = newValue.text;
      if (newValueText.length > 1 && newValueText[0].trim() == '0') {
        newValue = disallowZero.formatEditUpdate(oldValue, newValue);
        if (newValue.text.isEmpty) {
          return oldValue;
        }
      }
      if (newValueText.isNotEmpty) {
        return int.tryParse(newValueText) != null ? newValue : oldValue;
      }
      return newValue;
    })
  ];
}

And pass the formatters list to your TextField

... 
 child: TextField(
    ...
    inputFormatters: onlyUnsignedNumbers()
    ...
 )
...

This will disallow the leading 0 but will allow single 0 and all other positive numbers, if you want negatives too change the Regex from "[0-9]" to "[0-9-]"

Upvotes: 1

Ahmad Ellamey
Ahmad Ellamey

Reputation: 329

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 .

Upvotes: 1

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14865

Try below code:

TextFormField(
  keyboardType: TextInputType.phone,
  inputFormatters: [
    FilteringTextInputFormatter.deny(
      RegExp(r'^0+'),
    ),
  ],
),

Upvotes: 3

Related Questions