Hi, anyone out there have a good regex for zip code validation that accepts a zip in either 5 digit or 5 plus 4 (90301-1111)? I'm trying to write one:
/\d{5}(-\d{4}$)?/
When I make the -1111 optional, it won't reject partials (i.e. 90301-11). Is it possible to do this in one step or will I need to do it in multiple steps?
Regex for zip code validation
the simplest way would be to write two regexes - one for 5 digits and one for 5-4 - and use them in an if regex1 or regex2 then woohoo! else doh!.
Unless you're a regex masochist
Thanks for the reassurance. I'd prefer to avoid death by regex, so I'll take your "iffy" advice. Thx again.
The problem is that you have the $ inside the optional part. So the end of your expression is not anchored to the end of the string. Try this:
/\d{5}(-\d{4})?$/
keep in mind, the whole world doesn't use US style zip codes... Canada uses letters.
Be careful when validating locale specific data.
[edit:] Canada is just an example. There are many many others.