Home > Blockchain >  TextFormField clears input text even if the Regex expression is satisfied
TextFormField clears input text even if the Regex expression is satisfied

Time:03-19

I'm using RegExp for positive decimal numbers

TextFormField(
  keyboardType: TextInputType.numberWithOptions(decimal: true),
  inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r'^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$')),
  ],
)

But when I enter something like 1.x, the TextFormField deletes the entire input. What am I doing wrong?

CodePudding user response:

the issue is that your regular expression don't give you the ability to have a . without a digit after it. you can copy past x.y but you can't type it one char at a time. the solution would be relative to what you want and prioritize, but I think this regex might solve the issue :

r'^\s*(?=.*[1-9])\d?\.*(?:\d{1,2})?\s*$'

CodePudding user response:

The \.\d{1,2} part matches two char sequence, . and then one or two digits.

The point here is that you need to allow a . char even if there is zero, one or two digits. To do this, you need to change \d{1,2} to \d{0,2}:

FilteringTextInputFormatter.allow(RegExp(r'^\s*(?:0|[1-9]\d*)(?:\.\d{0,2})?\s*$'))

Details:

  • ^ - start of string
  • \s* - zero or more whitespaces
  • (?:0|[1-9]\d*) - 0 or a non-zero digit followed with zero or more digits (NOTE that this means no 00 or 01 at the start of a number is allowed, but 100 is allowed; also it means the digit must exist in the input, it should be typed in first (deduced from (?=.*[1-9]) in your pattern))
  • (?:\.\d{0,2})? - an optional sequence of a . and then zero, one or two digits
  • \s* - zero or more whitespaces
  • $ - end of string.

See the regex demo.

NOTE that if you want to be able to start typing with whitespace, you need to make (?:0|[1-9]\d*) optional with a ?: (?:0|[1-9]\d*)?.

  • Related