快速入手
1.引入jQuery库和validation插件
<script src="../../scripts/jquery.js" type="text/javascript"></script>
<script src="lib/jquery.validate.js" type ="text/javascript">
2.确定哪个表单需要被验证
$("#commentForm").validate();
3.针对不同的字段,进行验证规则编码,设置字段相应的属性
- class = "required"为必须填写,minlength="2"为最小长度为2
- class="required emali"为必须填写,还有内容必须符合E-mail格式
- class = "url"为URL格式验证
fieldset为组合表单中的相关元素:
举例子如下:
<form>
<fieldset>
<legend>health information</legend>
height: <input type="text" />
weight: <input type="text" />
</fieldset>
</form>
自己做的一个小小demo,效果图如下:
代码如下:
<!DOCTYPE html>
<html>
<head>
<title>validation</title>
<meta charset="utf-8">
<script type="text/javascript" src = "jquery.js"></script>
<script type="text/javascript" src = "jquery.validate.js"></script>
</head>
<body>
<form id="comment">
<fieldset>
<legend>姓名和性别</legend>
<p>
<label for="cusername">姓名:</label>
<input type="text" name="username" class="required" minlength="2">
</p>
<p>
<label for="usersex">性别:</label>
<input type="text" name="usersex" class="required email" >
</p>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#comment").validate();
});
</script>
</body>
</html>
不同的验证方法###
1.引入一个新的jQuery插件——jquery.metadata.js
<script src="jquery.metadata.js" type=""text/javascript></script>
2.改变验证方法为
$(#commentFrom).validate({meta:"validate"});
3.将验证规则全部编写到class属性中
class="{validate:{required:true,minlength:2}}"
代码如下:
<!DOCTYPE html>
<html>
<head>
<title>validation</title>
<meta charset="utf-8">
<script type="text/javascript" src = "jquery.js"></script>
<script type="text/javascript" src = "jquery.validate.js"></script>
<script src="jquery.metadata.js" type=""text/javascript></script>
</head>
<body>
<form id="comment">
<fieldset>
<legend>姓名和性别</legend>
<p>
<label for="cusername">姓名:</label>
<input type="text" name="username" class="{validate:{required:true, minlength:2}}">
</p>
<p>
<label for="usersex">性别:</label>
<input type="text" name="usersex" class="{validate:{required:true, minlength:2}}" >
</p>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#comment").validate({meta:"validate"});
});
</script>
</body>
</html>
另一种可以做到行为和结构完全分离的
1.将字段中的class属性全部移除
2.加入如下jQuery代码
$(document).ready(function(){
$(""#comment).validate({
rules: {
username: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
url:"url",
comment: "required"
}
});
})