Home > front end >  Flutter TextFormField inputFormatters regular expression (RegEx) doesn't work
Flutter TextFormField inputFormatters regular expression (RegEx) doesn't work

Time:12-16

I want to have a regular expression in flutter on my TextFormField, that only numbers between -999 & 999 can be put in. When I tested the expression everything worked how I wanted to, but I don't know why I can not write "-" in the TextFormField. The maximum numbers and that a number should not start with 0 works perfectly fine, but all the time I try to add a minus it doesn't work. I would be thankful for any help!

 TextFormField(
              decoration: kTextFieldDecoration,
              style: kCustomNumberBoxTextStyle,
              keyboardType: TextInputType.numberWithOptions(signed: true),
              textAlign: TextAlign.center,
              initialValue: number.toString(),
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(r'^-?[1-9]([0-9]{1,2})?')),
              ],
              onChanged: (String newValue) {
                if (newValue != "") {
                  setState(() {
                    number = int.parse(newValue);
                  });
                  widget.onTap(int.parse(newValue));
                }
              },
            ),

CodePudding user response:

Your ^-?[1-9]([0-9]{1,2})? regex makes the initial hyphen optional, which is fine, but the [1-9] part requires a non-zero digit. Moreover, you missed the $ anchor at the end, and the regex can match anything after the third digit.

In order to be able to insert a single -, you need to make the digit matching parts optional.

You can thus use

^-?(?:[1-9][0-9]{0,2})?$

See the regex demo. Details:

  • ^ - start of string
  • -? - an optional - char
  • (?:[1-9][0-9]{0,2})? - an optional sequence of
    • [1-9] - a non-zero digit
    • [0-9]{0,2} - any zero, one or two digits
  • $ - end of string.
  • Related