用于表单验证

Validate是jQuery插件,必须在JQuery的基础上进行运行。所以必选导入jQuery库,validate库,和国化资源库(可选)

使用前提

jQuery-validation

errorPlacement:function(error,element) {error.appendTo(element.parent()); }

 指明错误放置的位置,默认情况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面。

success:function(succ,element){

succ.addClass("success");

}

 要验证的元素通过验证后的动作,如果跟一个字符串,会当作一个 css 类,也可跟一个函数。

 

jQuery-validation

jQuery-validation

例子:

注意:radio控件后面必须写一个label标签,class必须是error,for必须指向radio的name属性

<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			label.error{
				background-image:url(img/unchecked.gif);
				background-size: 12px;
				padding-left:20px ;
				background-repeat: no-repeat;
				color:red;
			}
			label.success{
				color: green;
				background-image: url(img/34.png);
			}
		</style>
		<script type="text/javascript" src="js/jquery-3.2.1.js" ></script>
		<script type="text/javascript" src="js/jquery.validate.js" ></script>
		<script type="text/javascript" src="js/messages_zh.js" ></script>
		<script>
			$(function(){
				$("#vali").validate({
					rules:{
						user:{
							required:true,
							maxlength:6
						},
						password:{
							required:true,
							digits:true,
							minlength:5
						},
						repassword:{
							required:true,
							equalTo:"[name=password"
						},
						emil:{
							required:true,
							email:true
						},
						sex:{
							required:true
						}
					},
					messages:{
						user:{
							required:"用户名不可以为空",
							maxlength:"长度至少为六位"
						},
						password:{
							required:"密码不可以为空",
							digits:"必须为数字",
							minlength:"长度至少六位"
						},
						repassword:{
							required:"确认密码必填",
							equalTo:"两次密码输入不一致"
						},
						emil:{
							required:"邮箱不可为空",
							email:"邮箱格式不正确"
						},
						sex:{
							required:"性别必须勾选"
						}
					},
					success:function(succ,element){
						succ.addClass("success");
					},
					errorElement:"label"
				});
			});
		</script>
	</head>
	<body>
		<form action="#" id="vali">
			<p>用户名:<input type="text" name="user" /></p>
			<p>密码:<input type="password" name="password" /></p>
			<p>确认密码:<input type="password" name="repassword" /></p>
			<p>邮箱:<input type="text" name="emil" /></p>
			<p>性别:男<input type="radio" name="sex" value="man"/>
			女<input type="radio" name="sex" value="woman"/>
			<label for="sex" class="error" style="display: none;"></label>
			</p>
			<input type="submit" value="提交" />
		</form>
	</body>
</html>

 

相关文章: