skip to Main Content

I have the following input formatter on my TextField

 inputFormatters: [
     FilteringTextInputFormatter.allow(
         RegExp(r'^+[0-9]+'),
     ),
 ],

And it doesn’t allow me to type a + on the start of a phone number. So I decided to test it in dartpad.

void main() {
  final regex = RegExp(r'^+[0-9]+');
  print(regex.hasMatch('+310612345678'));
}

Which outputs true. What am I doing wrong?

2

Answers


  1. Ahh… you discovered why most complex filters are doomed to fail.

    Think about it this way… to type "+123" you must first type "+". But "+" isn’t allowed by your filter! And even if it was, that would mean you could also submit just a "+"!

    So the solution would be to put this as the validation regex instead. If you insist, you can run the validation check on each change instead of on submit, which would give you an error on empty string or +, but let you eventually type +123 as valid.

    Login or Signup to reply.
  2. If you want to allow the + sign in the input, you can modify the regular expression to ^[+0-9]+. This regular expression pattern specifies that the input must start with either a + or a digit, followed by one or more digits. Here’s the updated code:

    inputFormatters: [
     FilteringTextInputFormatter.allow(
         RegExp(r'^[+0-9]+'),
     ),
    

    ],

    With this format, the input field will allow the + sign and digits and block any other characters.

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