【问题标题】:Waiting for Google Geocoder results in a jquery custom validation method等待 Google Geocoder 导致 jquery 自定义验证方法
【发布时间】:2016-03-08 22:28:47
【问题描述】:

我知道 Google 的地理编码器服务是异步的,但我需要一种方法来在 google 地理编码器结果返回之后而不是之前返回 true 或 false 到我的自定义 jQuery Validate 方法。 (例如,该服务将查找邮政编码,如果找到则返回 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;
         }
       }
     };

【问题讨论】:

  • "Code sn-ps" 用于在此页面中运行 JavaScript 代码。由于您无法在此页面上运行您的代码,因此我删除了 sn-p。
  • 如果您只想在输入第 5 位数字后运行验证,则必须更改触发验证的方式。尝试将onkeyup 设置为false... 然后验证只会在focusoutsubmit 事件上触发。如果您想将此行为限制为一个字段,则需要为 onkeyup 编写一个包含条件的自定义函数。 See plugin options.
  • 你知道我在哪里可以找到 onkeyup 的自定义函数示例吗?
  • 可以看插件源码中的函数

标签: javascript jquery google-maps jquery-validate google-geocoding-api


【解决方案1】:

As I mentioned in my comment,拉取默认的onkeyup 函数from the plugin 并修改它以供您覆盖。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多