问题
I know Google's Geocoder service is asynchronous, but I need a way to return true or false to my custom jQuery Validate method after the google geocoder results have returned and not before. (ex. the service will look up a zip code, if found return true, else return false).
Edit - Is jQuery Validate remote
method the way to do it?
Currently I have a set of rules for the element, but when I test this code below the getLocation
method gets called as soon as the code is loaded, not when a 5th digit is entered like I want.
$('#Location').rules("add", {
required: true,
minlength: 5,
maxlength: 5,
messages: {
required: "Required input",
minlength: jQuery.validator.format("Please, {0} characters are necessary"),
maxlength: jQuery.validator.format("Please, {0} characters are necessary")
},
remote: getLocation()
});
function getLocation() {
var i = 0;
}
Here is my custom method.
$.validator.addMethod("validateZipCode", function(value, element) {
var isValidZipCode = GetGoogleGeocoderResultsByZip(value);
return zipCodeIsValid;
}, "Invalid location");
//the geocode results work something like this, but I need to wait to return true/false
function GetGoogleGeocoderResultsByZip(zipCode) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode("componentRestrictions": {
"country": "United States",
"postalCode": zipCode
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results.length >= 1) {
return true;
}
return false;
}
}
};
回答1:
As I mentioned in my comment, pull the default onkeyup
function from the plugin and modify it for your over-ride.
$("#contact").validate({
onkeyup: function(element, event) {
if (element.name == "zip-code") {
return; // no onkeyup validation at all
} else {
// default onkeyup validation in here
var excludedKeys = [
16, 17, 18, 20, 35, 36, 37,
38, 39, 40, 45, 144, 225
];
if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {
return;
} else if ( element.name in this.submitted || element.name in this.invalid ) {
this.element( element );
}
}
},
....
In the proof-of-concept DEMO below, hit the submit
button to first get past the "lazy" validation, then compare the behavior of the two fields. The first field is validating for an email address on every keyup
event. The second field is not validating for email on keyup
events at all, only on focusout
and submit
.
DEMO: http://jsfiddle.net/vbcpyv3q/
来源:https://stackoverflow.com/questions/35879293/waiting-for-google-geocoder-results-in-a-jquery-custom-validation-method