code show as below:
jQuery.validator.addMethod("isEx",
//value代表的是表单传入的值
//element代表的是标签类型
params代表的rules里面写的东西
function(value, element, params)
{
var flag=false;
$.ajax({
//这一块必须打开同步,不然ajax还没有运行完毕,return就已经返回了
async:false,
//自动访问isExServlet进行查询是否存在用户
url:"${pageContext.request.contextPath}/isEx",
//查询完后data接收servlet的返回结果对应的还有一个error函数
success:function(data)
{
if(data.isEx==true)
flag=true;
},
//这个data和函数中的不一样,这是向servlet发送的data数据
data:{"username":value},
//datatype代表的是servlet向success函数和error函数返回数据的类型
dataType:"json",
//提交数据的方式
type:"Post"
});
return !flag;
},
//format中显示错误提示
jQuery.validator.format("用户已经存在"));
isEx is a custom rule. Synchronization must be used in this ajax, otherwise ajax has not assigned a value to the flag, and return has already returned the value.
Add one more: optional(element): validation is triggered only when the value of the form control is not empty, and validation is also triggered when the value is empty (this function is available in many custom methods)