我已经创建了一个像这样的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的输出为true,则表示验证成功,我们不需要显示任何错误消息,否则显示错误消息。但是现在,我首先在表单上输入了什么,它显示为错误,从第二次开始,它显示验证成功。任何人都可以指出我在这里做错了吗?
答案 0 :(得分:1)
有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;
答案 1 :(得分:1)
试试这个。
var response= false;
$.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 === "true" ? true : false;
}
});
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) {
}
});