简体   繁体   English

自定义jQuery.validator规则出现问题

[英]Problem with custom jQuery.validator rule

I'm having a problem with this code that I can't seem to figure out: 我对此代码有疑问,似乎无法解决:

$.validator.addMethod('street_address', function (value, element) {
  var address  = value + ', ' + $(element).parent().parent().find("#venue_city_id option:selected").text(),
      geocoder = new google.maps.Geocoder(),
      that     = this;
  geocoder.geocode({address: address}, function (results, status) {
    return that.optional(element) || status == google.maps.GeocoderStatus.OK;
  });
}, 'invalid address');

It works to invalidate an incorrect address (one that is not geocodeable by Google). 它可以使不正确的地址(Google无法对其进行地理编码的地址)无效。 The problem is even when it returns true, I'm still getting 'invalid address'. 问题是即使返回true,我仍然会收到“无效地址”。 Any ideas on what the problem might be? 关于可能是什么问题的任何想法?

You return from inside callback in 您从内部回调返回

geocoder.geocode({address: address}, function (results, status) {
    return that.optional(element) || status == google.maps.GeocoderStatus.OK;
});

Not from validator function. 不是来自验证器功能。

Moreover, geocoder.geocode performs, I believe, asynchronous ajax query, so you'll not be able to tell whether your location is "geocodeable" when leaving you validator. 此外, geocoder.geocode执行,我相信,AJAX的异步查询,所以你不能就能够告诉你离开时,验证您的位置是否是“geocodeable”。 There should be a specific validator for such cases in jQuery validation, called remote or something, which validates basing on the result of ajax query. 在jQuery验证中,应该有一个针对此类情况的特定验证器,称为remote或诸如此类,该验证器基于ajax查询的结果进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM