Antony
Antony

Reputation: 791

Why regex behave differently from string in Angular Form Validator

This validator for my form control behaves differently based on the declaration (even thou the method interface can accept RegExp or string). For example, when I paste username in the input and then paste white space, the first example of the pattern does not validate the error, unlike the second one.

Regex String regex

Upvotes: 0

Views: 456

Answers (2)

Geoff Bomford
Geoff Bomford

Reputation: 1

I think the documentation should include an example where a regex is passed as the pattern.

The following email pattern fails...

Validators.pattern('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$')

However passing the regex works as expected...

Validators.pattern(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/)

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

It's unfortunataly not documented, but when you pass a string, Angular adds ^ at the beginning (if not present yet) and $ at the end (if not present yet). If you pass a Regexp, it uses it as is.

See the source code.

Upvotes: 2

Related Questions