Zeus82
Zeus82

Reputation: 6375

Angular 2 Reactive Forms 'pattern' validator not working

I have defined the following validation:

            Validators.pattern("/^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$/")]]

Its to validate postal codes, but when I enter the string 'K1K1A1' the validator says its invalid.

What is wrong with my regex?

Upvotes: 0

Views: 2821

Answers (1)

Serginho
Serginho

Reputation: 7490

Validators.pattern() looks like:

if (typeof pattern === 'string') {
  regexStr = `^${pattern}$`;
  regex = new RegExp(regexStr);
} else {
  regexStr = pattern.toString();
  regex = pattern;
}

So, just remove slashes and ^$ characters to fit with angular. Or you also remove quotes and javascript will take your expression as a RegExp type.

Upvotes: 7

Related Questions