Validator remote method, matching value to JSON array-Collection of common programming errors
Aloha!
Trying to run a basic validation on a postal code input, and additionally check the entered value to see if it exists in a keyless JSON array. Everything works as expected until I add the remote function. If possible, I’d like to utilize this function, since it is built in, but I am open to other methods of validation.
Working example of this, without remote, here: http://jsfiddle.net/sangria/xLGae/
Likely unrelated, but getting this error in the console on submit:
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
JSON array format:
[94102,94117,94110,99950,...]
jQuery and Validation:
jQuery.validator.addMethod("postalcode", function(postalcode, element) {
return this.optional(element) || postalcode.match(/^([0-9]{5})$/);
}, "Please specify a valid postal/zip code");
$("#postal").validate({
rules: {
zipcode: {
required: true,
postalcode: true,
digits: true,
minlength: 5,
maxlength: 5,
remote: {
type: 'post',
contentType: 'application/json; charset=utf-8',
url: "data/uszipsonly.json",
dataType: 'json',
async: false
}
}
},
messages: {
zipcode: { remote: "Please specify a US postal code"}
}
});
Pored over the docs and some other good examples. Found similar threads here on SO, but still somewhat tripped up by this.
Much thanks to the community for any enlightenment.
-
If you are using the jquery.bassistance.de like I think maybe you mis-interpreted the role of the remote feature..
Basically remote can only return true/false after being sent the value and is intended mainly for rules were you don’t want the accepted value to be stored on the client, EVER (think of captcha for example) like in here http://jquery.bassistance.de/validate/demo/captcha/
If you want to download the list of possible ZIP code your app accept (or does not accept) from your server I suggest doing the following:
$.getJSON("data/uszipsonly.json", function(response) { var validZIP = response; jQuery.validator.addMethod("postalcode", function(postalcode, element) { return this.optional(element) || (postalcode.match(/^([0-9]{5})$/) && $.inArray(postalcode, validZIP)); }, "Please specify a valid postal/zip code");
})
Originally posted 2013-11-13 09:49:02.