Home > Software design >  Allow some characters in flutter field input Regex
Allow some characters in flutter field input Regex

Time:08-26

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 ' .

CodePudding user response:

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/'‘’-] $'''

CodePudding user response:

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.\u0030-\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

  • Related