1

I have a TextField that i am using to get a double in my flutter app. The TextField uses number keypad.

   child: TextField(
        style: TextStyle(color: Colors.white),
        inputFormatters: [FilteringTextInputFormatter.allow(new RegExp("[0-9.]"))],
        controller: controller,
        keyboardType: TextInputType.number,
        decoration: textDecorator,
        onSubmitted: () {
          //Some Action
        },
      ),

I have used inputformatter to prevent user from clicking on other punctuations as shown in the code. My issue is i am able to enter something like "23.45.3" which is basically having two "." symbols which should not be allowed. Ideally after "23.", if the user tries to click "." from the keypad again it should be disabled. Any help on how to do this is appreciated.

Hari
  • 15
  • 2
  • look here https://stackoverflow.com/q/54454983/3660991 – HasilT Sep 16 '21 at 13:40
  • Thankyou for your reply. That solution just limits the number of digits after the decimal point. In my scenario the number of digits after the decimal point is not a problem. I can have values like 12.678979. But I can't have values like 1.2.3 or 1234.69890.097. – Hari Sep 16 '21 at 13:52

1 Answers1

0

The regex you are using matches any single instance of a digit or a number, so as long as any of those are present anywhere in your input, then the formatter will allow it. Instead you can try something like this:

FilteringTextInputFormatter.allow(new RegExp("^-?([1-9]\d+|0)(\.\d+)?$"))
  • the ^ and $ indicate the beginning and end of the line of input, which forces the entire string to match the regex
  • -? indicates the first character could be 0 or 1 instance of the - symbol. You can remove this if you don't want to allow negative numbers
  • ([1-9]\d+|0) allows any character of digits starting with a non-0 digit ([1-9]\d+) OR a single 0 (|0). You can make this piece to be just \d+ if you are ok with multiple leading 0s.
  • the last piece, (\.\d+)? allows for the decimal point (\., escaped with \ because a . alone is a special character in regexes) followed by at least one digit (this prevents numbers with no characters after the decimal point like 3.). The ? indicates that this pattern can appear at most once, preventing allowing more than one decimal point.

I haven't actually tested this as in input formatter though, and I anticipate there might be issues with inputting a decimal point in the first place due to the fact that the regex enforces a decimal point be followed by a digit. If that does end up being the case, you can try using "^-?([1-9]\d+|0)(\.\d*)?$" instead (the last ? -> *), but then you would have to do some further validation on your own to prevent numbers like 3. on submission, if that is an issue for you.

anqit
  • 780
  • 3
  • 12