4

I could anybody help me out?

I am looking for some regexp to use to validate US Zip codes and Canadian Postal codes in AngularJS

Himanshu Patel
  • 173
  • 1
  • 2
  • 7
Sonia Brami
  • 127
  • 1
  • 1
  • 10

1 Answers1

9

This should work for you:

^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] *\d[A-Z]\d)$

http://regex101.com/r/nO4zF5

Remove the ^ and $ anchors if you don't want to match the start and end of the string.

When using in Javascript remember that you need to use the / delimiter:

if (/^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] *\d[A-Z]\d)$/.test(str)) {
    // it's a match!
}

And directly, as an Angular ng-pattern:

ng-pattern="/^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] *\d[A-Z]\d)$/"
brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • 1
    I didn't realize I had to put slashes at the beginning and the end of the expression, I am all good now, thank you remus /^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] *\d[A-Z]\d)$/ – Sonia Brami Jan 17 '14 at 23:36
  • 1
    Yes, that's how you denote a regular expression in .js ;) – brandonscript Jan 17 '14 at 23:40
  • Thanks. It would be nice if the example was in the angular js context. I had to read the comments to figure it out. Would be helpful for other noobs like me. – Gene Parcellano Nov 30 '15 at 16:58
  • Trouble with that Gene is that the other half of people will think that's part of the expression – brandonscript Nov 30 '15 at 16:59