我正在尝试验证输入到表单字段的邮政编码是否对从前一个字段中的下拉列表中选择的状态有效。我有一个表中的所有数据,并能够使用ajax调用确认。我下面的代码允许我将ajax调用返回true / false,但我不确定如何根据返回值触发验证。有没有人有想法?
自定义验证:
ko.validation.rules["isValidZipCode"] =
{
getValue: function (o) {
return (typeof o === 'function' ? o() : o);
},
validator: function (val, fields) {
var self = this;
var anyOne = ko.utils.arrayFirst(fields, function (field) {
var val = self.getValue(field);
if (val === undefined || val === null)
return "";
return true;
});
var ajaxData = { state: anyOne, zipCode: val }
$.ajax({
url: $("a#ValidateZipByState").attr("href"),
type: "POST",
data: ajaxData,
success: function (isValid) {
if (isValid) {
return true;
} else {
return false;
}
},
error: handleSubmitError
});
return;
},
message: "Invalid zip code for this state"
};
视图模型:
self.State = ko.observable(model.State).extend({ required: true });
self.ZipCode = ko.observable(model.ZipCode).extend({ required: true, pattern: /^[0-9]{5}(?:-[0-9]{4})?$/g, isValidZipCode: [self.State, self.ZipCode] });
答案 0 :(得分:1)
您正在进行异步验证。您需要处理validator
的第三个参数:
validator: function (val, fields, callback) {
var self = this;
var anyOne = ko.utils.arrayFirst(fields, function (field) {
var val = self.getValue(field);
if (val === undefined || val === null)
return "";
return true;
});
var ajaxData = { state: anyOne, zipCode: val }
$.ajax({
url: $("a#ValidateZipByState").attr("href"),
type: "POST",
data: ajaxData,
success: function (isValid) {
if (isValid) {
callback(true); // HERE
} else {
callback(false); // HERE
}
},
error: handleSubmitError
});
return;
},
答案 1 :(得分:1)
看起来您需要在验证定义上设置async标志,然后您可以将结果返回给callback参数。 Reference
ko.validation.rules["isValidZipCode"] =
{
async: true,
getValue: function (o) {
return (typeof o === 'function' ? o() : o);
},
validator: function (val, fields, callback) {
var self = this;
var anyOne = ko.utils.arrayFirst(fields, function (field) {
var val = self.getValue(field);
if (val === undefined || val === null)
return "";
return true;
});
var ajaxData = { state: anyOne, zipCode: val }
$.ajax({
url: $("a#ValidateZipByState").attr("href"),
type: "POST",
data: ajaxData,
success: function (isValid) {
callback(isValid);
},
error: handleSubmitError
});
return;
},
message: "Invalid zip code for this state"
};