我创建了一个像这样的 Jquery 自定义验证器
var response;
$.validator.addMethod(
"uniqueUserName",
function (value, element) {
$.ajax({
type: "POST",
url: "/umbraco/surface/MemberShipSurface/ValidatePostCode",
data: JSON.stringify({ PostCode: value }),
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg.istrue);
response = msg.istrue;
}
});
return response;
},
"wrong postcode"
);
$("#reg-form").validate({
rules: {
day: {
required: true,
range: [01, 31]
},
PostCode: {
required: true,
number: true,
maxlength: 4,
minlength: 4,
uniqueUserName: true
}
},
errorElement: "span",
submitHandler: function (form) {
}
});
如果 ajax 的输出为真,则表示验证成功,我们不需要显示任何错误消息,否则显示错误消息。但是现在我首先在表格上输入的任何值都显示为错误,从第二次开始它显示验证成功。谁能指出我在这里做错了什么?
最佳答案
有remote-method可用你可以像这样使用它,
rules: {
day: {
required: true,
range: [01, 31]
},
PostCode: {
required: true,
number: true,
maxlength: 4,
minlength: 4,
remote: {
url: "/umbraco/surface/MemberShipSurface/ValidatePostCode",
type: "post",
data: {
PostCode: function() {
return $( "#PostCode" ).val();
}
}
}
}
}
如果您想使用自定义方法,请在 $.ajax() 中使用 async=false
像这样打电话
var response=false;
$.ajax({
type: "POST",
async:false,// now it will wait until you get response
url: "/umbraco/surface/MemberShipSurface/ValidatePostCode",
data: JSON.stringify({ PostCode: value }),
contentType: "application/json; charset=utf-8",
success: function (msg) {
response = msg.istrue;
}
});
return response;
关于javascript - Jquery 自定义验证器 - 检查值是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751595/