I am trying to have a TextFormField
which only accepts negative and positive number of 5 digits.
The following code but it does restrict digits only and up to 5, but it is not accepting a negative sign.
new TextFormField(
maxLines: 1,
keyboardType: TextInputType.number,
enableSuggestions: false,
inputFormatters: [
LengthLimitingTextInputFormatter(5),
FilteringTextInputFormatter.allow(RegExp(r'-?[0-9]')),
],
onChanged: (val) {},
);
I have tried the following regex: "-?[0-9]" but it does not allow the negative sign.
2
Answers
Change
RegExp(r'-?[0-9]')
toRegExp(r'-?[0-9]*')
. It’s not letting you input a "-" because your expression is saying that you must have a number, but just solely "-" invalidates that so the formatter doesn’t let you input the negative.The problem with using an input filter is that every intermediate string must also match the filter. Since your filter cannot match a minus sign "on the way to" typing "-3", it doesn’t work.
This is when you must abandon using input filters, and instead put your validation into the validator, which will be applied only when checked, and won’t prevent intermediate combinations from being typed enroute.