Help with jQuery validate and a Zip code restriction based on the 1st three digitss
I am assuming I need a regular expression here?
I have a zip code field and the zip codes must be in the city limits of Chicago. Luckily all the zip codes begin with 606. So I need to poll the input to make sure that the zip code entered is 5 digits and begin with the numbers 606:
My input is basic enough:
<label for="dzip"><span class="red">♥ </span>Zip:</label>
<input name="attributes[address_zip]" id="dzip" type="text" size="30" class="required zip-code" />
And then my script for city was easy enough. I just need to apply it to zip-code as well:
jQuery.validato开发者_高级运维r.addMethod("Chicago", function(value) {
return value == "Chicago";
}, '**Recipient must reside in Chicago City Limits**');
May help if I show how the plug-in functions for phone-numbers (US). Basically I need to translate this to zips:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
What does this part do/mean?:
phone_number.replace(/\s+/g, "")
I dropped in the phone part directly from an example on the validate site.
Final answer from all the great (and quick) input here was this:
jQuery.validator.addMethod("zip-code", function(zip_code, element) {
zip_code = zip_code.replace(/\s+/g, "");
return this.optional(element) || zip_code.length == 5 && zip_code.match(^606[0-9]{2}$);
}, "Please specify a City of Chicago Zip Code");
for the length use the .length property
if($('#dzip').val().length != 5)
return false;
for the 606 use the substr method
if($('#dzip').val().substr(0,3) != 606)
return false;
combined
$('#dzip').change(function(){
var val = $(this).val();
if(val.length != 5 || val.substr(0,3) != 606)
return false; //not valid
else
//do stuff here
})
Try this:
jQuery.validator.addMethod("chicago", function(zip, element) {
zip = zip.replace(/\s+/g, "");
return this.optional(element) || zip.match("^606[0-9]{2}$");
}, '**Recipient must reside in Chicago City Limits**');
The above code can be read as
- Add a method chicago to the validator plugin
- when the method is called strip all whitespace characters
- then if the field is not required and it is empty
- or if it is required and not empty and is 5 digits in length
- and the first 3 characters are 606
- return true
- else return false
Look at this jQuery plugin.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
you can use this regex "606[0-9][0-9]" and see if it can be matched. then you check whether the input is five digits since i think this regex will also match 606111.
精彩评论