www.webdeveloper.com
Results 1 to 3 of 3

Thread: What's wrong with this regex?

  1. #1
    Join Date
    Jul 2013
    Posts
    1

    What's wrong with this regex?

    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.
    Code:
    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.
    Code:
    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; I've done this in the past two validate against two different phone number formats - (xxx) xxx-xxxx or xxx-xxx-xxxx:
    Code:
    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. Where am I going wrong with this?
    Code:
    var patt1 = /((^[a-z]{2,},\s*[a-z]{2}$\i)|(^[0-9]{5}))/;
    I have a fiddle here: http://jsfiddle.net/EmmyS/fHkZU/

  2. #2
    Join Date
    Jul 2013
    Posts
    66
    How come youre '/i' changed into '\i'? This causes the problem. Seeing how the second check is digits only, you can just use the switch for the entire regular expression.

    However, personally I'd prefer to keep the two expressions separate as the validate separate things and combining them just makes the expression unnecessarily complex. Besides, having them separate allows you to actually know whether a city or a zip code was entered (might or might not be usefulů).

    You might also want to consider simplifying both expressions with some character classes, such as \d for digits.

  3. #3
    Join Date
    Jun 2008
    Posts
    106
    Yea, it was your \i in the RegExp. Add that 'i' tag to the end of the RegExp.

    http://jsfiddle.net/thetenfold/43eh9/

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles