ng-pattern for input text

379 Views Asked by At

I have the following input-form-control:

input.form-control(
    ng-model='controller.password'
    ng-minlength='1'
    ng-maxlength='8'
    name='password'
    type="{{ controller.passwordShowType }}"
    ng-pattern='controller.PASSWORD'
    required
)

in controller:

PASSWORD = /^[A-Za-z0-9!-@#$%^&*()+<>]{1,8}$/;

For this input I want to allow only these symbols:

 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()-+<>ABCDEFGHIJKLMNOP1234567890'

But if I use my regex as above, I can input ',' or '.' symbols. What's the correct regexp for this to work ?

1

There are 1 best solutions below

0
On BEST ANSWER

The problem with your regex is that you use !-@ inside your square brackets (character set). Regex thinks you're trying to say "match all chars between char ! and char @" (char code 33 - 64), not "use on of [!-@]". Place the hypen at beginning or the end of the character set, or escape it with a backslash.

See also http://www.regular-expressions.info/charclass.html

In most regex flavors, the only special characters or metacharacters inside a character class are the closing bracket ], the backslash \, the caret ^, and the hyphen -.

Basically, you have to put hyphens somewhere where they're not valid or escape them.

You can also enter your regex at http://regexr.com/ to get regex syntax highlighting - it makes the error rather obvious, seeing as the hyphen is colored differently.