Roger Wong
Roger Wong

Reputation: 57

Allow some characters in flutter field input Regex

I want to make my form field input to pass through a validator to allow only alphabets number and three symbols - ' / to pass.

r'^[A-Za-z0-9\s-/]+$';

I have done for all except for symbol ' . Once I add in ' symbols it will assume I close the statement on there. How can I put in the symbols ' .

Upvotes: 1

Views: 1062

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

First of all, always place - at the end of the character class, it is the safest method to use it inside brackets.

Next, adding ' to a single-quoted string literal is done with an escape single quote, \'. Since this does not work, I suspect the problem is that you have curly quotes.

Also, consider using triple-quoted string literals, r"""<pattern>""". This is the most convenient way of writing patterns with quotes.

So you can consider using

pattern = r'''^[A-Za-z0-9\s/'‘’-]+$'''

If there is some warning you get, escape these special chars

pattern = r'''^[A-Za-z0-9\s\/\'\‘\’\-]+$'''

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

If that singlequote is still bothering you and nothing else worked, then there is another way to achieve it. A little tedious way but works pretty well.

Try using below regex,

^[^\u0000-\u001f\u0021-\u0026\u0028-\u002c.\u003a-\u0040\u005b-\u0060\u007b-\uffff]+$

Basically this regex excludes the character ranges that are not valid in your character set. I can add detailed explanation once you confirm it works for you and it should as it doesn't have any singlequote in the regex which was causing problem.

Had to use Unicode notation to prohibit matching Unicode characters.

Check this demo for valid and invalid matches

Upvotes: 1

Related Questions