skip to Main Content

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


  1. ChangeRegExp(r'-?[0-9]') to RegExp(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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search