前端——JQuery表单验证插件

1、引入JQuery插件(依赖JQuery)

<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="js/jquery.validate.min.js" type="text/javascript"></script>

2、定义校验规则

键是标签的名字

$(function () {
	$("#myform").validate({
		rules:{
			"username":{"required":true,"checkUsername":true},	<!--自定义校验-->
			"password":{"required":true,"rangelength":[6,12]},
			"repassword":{"required":true,"rangelength":[6,12],"equalTo":"#password"},	<!--寻找id=password的标签,进行内容对比-->
			"email":{"required":true,"email":true},
			"sex":{"required":true},
			"birthday":{"required":true,"date":true},
			"checkCode":{"required":true}
		},
		messages:{
			"username":{"required":"用户名不能为空","checkUsername":"用户名已存在"},
			"password":{"required":"密码不能为空","rangelength":"密码长度6-12位"},
			"repassword":{"required":"密码不能为空","rangelength":"密码长度6-12位","equalTo":"两次密码输入不一致"},
			"email":{"required":"邮箱不能为空","email":"邮箱格式不正确"},
			"birthday":{"required":"出生日期不能为空","date":"请输入正确的日期格式"},
			"checkCode":{"required":"请输入验证码"}
		}
	})
})

3、定义错误标签样式

插件会自动寻找第一个匹配name=“xxx”的标签,在它后面添加一个错误标签(class="error")

所以单选框会出现错误,所以要在你想要在的位置加上如下代码:

<label class="error" for="sex" style="display: none">性别不能为空</label>

4、自定义校验规则

$.validator.addMethod(
	"checkUsername",

	function (value,element,params) {
		//value:输入的内容
        //element:被校验的元素对象
        //params:规则对应的参数值
        //目的:对输入的username进行ajax校验
		var flag = false;

		$.ajax({
			"async":false,	<!--是否异步-->
			"data":{"username":value},
			"dataType":"json",
			"type":"POST",
			"url":"${pageContext.request.contextPath}/checkUsername",
			"success":function (dat) {
				flag=dat.isExist;
			}

		});

		//返回false代表该校验器不通过
		return !flag;
	}
);

 

posted @ 2018-02-19 10:26  想54256  阅读(199)  评论(0编辑  收藏  举报