I have a location search field that needs to allow either a city and state, or a zip code. I have two separate regex patterns that each work separately, but am having issues combining them.
This one is for city and state; it checks to make sure that there are at least two letters, then a comma, an optional whitespace, and exactly two more letters. Works great.
var str="abc, de";
var patt1 = /^[a-z]{2,},\s*[a-z]{2}$/i;
if(patt1.test(str)) {
alert("true");
}
else {
alert("false");
}
This one is for zip codes. It checks to make sure there are exactly 5 numbers. Also works.
var str="01235";
var patt1 = /[0-9]{5}/;
if(patt1.test(str)) {
alert("true");
}
else {
alert("false");
}
I know you can do a match for alternatives by using parentheses and the pipe symbol; I've done this in the past two validate against two different phone number formats - (xxx) xxx-xxxx or xxx-xxx-xxxx:
var pattern = /((^\([0-9]{3}\) [0-9]{3}[-]{1}[0-9]{4}$)|(^[0-9]{3}-[0-9]{3}[-]{1}[0-9]{4}$))/;
But when I try to do this with my city/state and zip checks, it doesn't work. If I enter a zip code, it correctly returns true, but any and all combos of city and state return false, even when they correctly return true when the city/state pattern is used on its own. And it seems to be ignoring the requirement for exactly 5 numbers in the second possibility; it will return false if there are less than 5, but will return true if there are more than 5. Where am I going wrong with this?
var patt1 = /((^[a-z]{2,},\s*[a-z]{2}$\i)|(^[0-9]{5}))/;
I have a fiddle here: http://jsfiddle.net/EmmyS/fHkZU/