快速入手
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.針對不同的字段,進行驗證規(guī)則編碼蕾总,設(shè)置字段相應(yīng)的屬性
- class = "required"為必須填寫逃延,minlength="2"為最小長度為2
- class="required emali"為必須填寫捕虽,還有內(nèi)容必須符合E-mail格式
- class = "url"為URL格式驗證
fieldset為組合表單中的相關(guān)元素:
舉例子如下:
<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.將驗證規(guī)則全部編寫到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>
另一種可以做到行為和結(jié)構(gòu)完全分離的
1.將字段中的class屬性全部移除
2.加入如下jQuery代碼
$(document).ready(function(){
$(""#comment).validate({
rules: {
username: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
url:"url",
comment: "required"
}
});
})