0

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?

Zeus82
  • 6,065
  • 9
  • 53
  • 77

1 Answers1

7

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.

Serginho
  • 7,291
  • 2
  • 27
  • 52
  • Yes, removing quotes the typeof is equals RegExp. – Serginho Jun 11 '17 at 18:48
  • can you please help me to solve this https://stackoverflow.com/questions/52091334/password-validation-is-not-working-in-angular-5 @Serginho – Zhu Aug 30 '18 at 08:37