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*)-0or a non-zero digit followed with zero or more digits (NOTE that this means no00or01at the start of a number is allowed, but100is 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*)?.
