等待Google Geocoder会产生jquery自定义validation方法

我知道谷歌的Geocoder服务是异步的,但我需要一种方法,在谷歌地理编码器结果返回之后,而不是之前返回true或false到我的自定义jQuery Validate方法。 (例如,服务将查找邮政编码,如果发现返回true,否则返回false)。

编辑 – jQueryvalidationremote方法的方法吗?

目前我对元素有一套规则,但是当我在下面测试这段代码时,一旦加载代码就会调用getLocation方法,而不是像我想要的那样输入第5位数字。

 $('#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; } 

这是我的自定义方法。

  $.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; } } }; 

正如我在评论中提到的那样 , 从插件中提取默认的onkeyupfunction并修改它以便您进行覆盖。

 $("#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 ); } } }, .... 

在下面的概念validationDEMO中,点击submit按钮首先通过“懒惰”validation,然后比较两个字段的行为。 第一个字段是validation每个keyup事件的电子邮件地址。 第二个字段根本没有validationfocusout事件上的电子邮件,仅关注focusoutsubmit

演示: http : //jsfiddle.net/vbcpyv3q/