Javascript Jquery自定义验证器-检查值是否有效?
我创建了一个Jquery自定义验证器,如下所示Javascript Jquery自定义验证器-检查值是否有效?,javascript,jquery,validation,Javascript,Jquery,Validation,我创建了一个Jquery自定义验证器,如下所示 var response; $.validator.addMethod( "uniqueUserName", function (value, element) { $.ajax({ type: "POST", url: "/umbraco/surface/MemberShipSurface/Valida
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,则表示验证成功,我们不需要显示任何错误消息,也不需要显示错误消息。但现在,我在表格上输入的任何值,第一次显示为错误,第二次显示为验证成功。有人能指出我做错了什么吗?有可用的,你可以这样使用它
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();
}
}
}
}
}
如果要使用自定义方法,请在调用中使用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;
试试这个
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) {
}
});
声明此
var响应=false代码>不工作。与我上面提到的相同的问题再次发生在msg.istrue的值上?如果数据有效,则为true,如果数据错误,则为False。您可以创建一个小提琴吗?此代码没有显示任何错误消息,说明我输入的任何数据以及您在msg.istrue
中返回的值?