anonymous-dev
anonymous-dev

Reputation: 3489

Input formatter doesn't allow value when it should

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?

Upvotes: 0

Views: 75

Answers (2)

Randal Schwartz
Randal Schwartz

Reputation: 44056

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.

Upvotes: 3

Abdul Rehman Shaikh
Abdul Rehman Shaikh

Reputation: 46

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.

Upvotes: 1

Related Questions