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

Waiting for Google Geocoder results in a jquery custom validation method

本文关键字:jquery 自定义 验证 方法 Google Geocoder 等待      更新时间:2023-09-26

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

编辑 - jQuery Validate remote方法是否有效?

目前我对元素有一组规则,但是当我在下面测试此代码时,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;
         }
       }
     };

正如我在评论中提到的,从插件中提取默认的onkeyup函数并对其进行修改以进行覆盖。

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

在下面的概念验证 DEMO 中,点击submit按钮首先通过"懒惰"验证,然后比较两个字段的行为。 第一个字段是验证每个keyup事件的电子邮件地址。 第二个字段根本不验证keyup事件的电子邮件,仅在focusoutsubmit上验证。

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