Solved

US Zipcode range validation with jQuery validation plugin

Posted on 2014-12-18
1
181 Views
Last Modified: 2015-01-07
The jQuery validation plugin additional methods provides an example for zipcode range validation. This same example appears within numerous posts on the internet as an example of doing zipcode range validation, but I have found no discussion as to how to expand the range beyond the narrow scope used in this example.

jQuery.validator.addMethod("ziprange", function(value, element) {
    return this.optional(element) || /^90[2-5]\d\{2\}-\d{4}$/.test(value);
}, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");

How would I rewrite this function, using regex or otherwise, to validate the range of valid US zipcodes (00544 - 99500) while still allowing for 9-digit zips? I mention this final condition because I have tried using the more basic "range" validation [544, 99950] but it fails to accommodate 9-digit zips and invalidates any input of 6 or more digits.
0
Comment
Question by:lynnwalker
1 Comment
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 40507890
jQuery.validator.addMethod("ziprange", function(value, element) {
    var v = value.replace(/^90[2-5]|-/g, "") * 1; // remove third first digits and dash and create a numeric 
    var testZip = v > = 544 && v < 99500 && /^90[2-5]\d\{2\}-\d{4}$/.test(value);
    return this.optional(element) || testZip;
}, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");

Open in new window

0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question