Michal Žídek
Michal Žídek

Reputation: 494

Flutter TextField TextInputFormatter wipes whole string on entering not allowed character

So I have normal TextField, like this:

                TextField(
                          autofocus: true,
                          controller: _textController,
                          keyboardType: TextInputType.text,
                          inputFormatters: <TextInputFormatter>[
                            FilteringTextInputFormatter.allow(RegExp(
                                r'^[A-zÀ-ÖØ-öø-įĴ-őŔ-žǍ-ǰǴ-ǵǸ-țȞ-ȟȤ-ȳɃɆ-ɏḀ-ẞƀ-ƓƗ-ƚƝ-ơƤ-ƥƫ-ưƲ-ƶẠ-ỿ\s*&^%0-9,.-:)(]+$')),
                          ],
                          style: TextStyle(
                            color: Colors.amber,
                          ),
                          decoration:
                              InputDecoration(fillColor: Colors.transparent),
                          maxLines: null,
                        ),

Everything works fine, until I write character which is not allowed into the field, then whole string vanishes. I dig into it and find out that FilteringTextInputFormatter.allow has property which is called replacementString which is by default as empty string. Now the question is, how exactly should I work with this, since if I add a listener to text controller and monitor changes, I don't know if user deleted the text or if user entered not allowed character. Well as far as I know.

Is there some method which just prevents to enter character with RegEx, I don't want text to get deleted, I just want prevent entering the not allowed character. Is there some way of achieving this without listeners or other methods which do this sort of checking?

Upvotes: 3

Views: 2029

Answers (1)

Michal Ž&#237;dek
Michal Ž&#237;dek

Reputation: 494

So the solution for this is simple, the RegEx should not have $ sign at the end, I am answering this just in case someone might find this useful.

Instead of this:

FilteringTextInputFormatter.allow(RegExp(
                                r'^[A-zÀ\s*&^%0-9,.-:)(]+$'))

It needs to be like this, for proper functionality:

FilteringTextInputFormatter.allow(RegExp(
                                r'^[A-zÀ\s*&^%0-9,.-:)(]+'))

Upvotes: 18

Related Questions