【发布时间】: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... 然后验证只会在focusout和submit事件上触发。如果您想将此行为限制为一个字段,则需要为onkeyup编写一个包含条件的自定义函数。 See plugin options. -
你知道我在哪里可以找到 onkeyup 的自定义函数示例吗?
-
可以看插件源码中的函数
标签: javascript jquery google-maps jquery-validate google-geocoding-api