概述:jquery.validate.js是jquery下的一個驗證插件。
官網:http://bassistance.de/jquery-plugins/jquery-plugin-validation/
中文API:http://download.csdn.net/source/2423908
實戰使用:
1.引用jquery基礎包和valiedate插件包
<script src="../js/jquery/jquery.js" type="text/javascript"></script>
<script src="../js/jquery/jquery.validate.js" type="text/javascript"></script>
注:這裡不能将引用寫反。
2.編輯發生驗證錯誤時提示的css
<style type="text/css">
#frmMain label.error
{
color: red;
margin-left: 10px;
width: auto;
display: inline;
}
input.error
{
border: 1px dotted red;
}
</style>
注:這個可以根據具體的實作進行修改。
3.定義驗證規則(本人在項目中使用的時候是定義了一個單獨的js檔案,比如資訊添加——
Information_Create.aspx和資訊的修改——Information_Edit.aspx這兩個頁面都需要進驗證,那麼我就定
義一個js檔案——information.js在兩個頁面都可以重用。),information.js驗證如下:
$.validator.setDefaults({
submitHandler: function(form) {
form.submit();
}
});
$(document).ready(function() {
$("#frmMain").validate({ //這裡的frmMain是我們的<from></form>标簽的id
rules: {
txtName: {
required: true
},
txtAuthor: {
required: true
},
txtSource:{
required: true
},
hidType:{
required: true
},
ddlState: {
required: true
},
ddlPutType:{
required: true
}
},
messages: {
txtName: {
required: "标題不能為空!"
},
txtAuthor: {
required: "作者不能為空!"
},
txtSource:{
required: "來源不能為空!"
},
hidType:{
required: "請選擇資訊歸屬!"
},
ddlState: {
required: "請選擇資訊稽核狀态!"
},
ddlPutType:{
required: "請選擇資訊推薦位!"
}
}
});
});
注:這裡隻是舉了自己在實戰中的一個小例子,還有一些驗證規則,大家可以通過通路官網或者下載下傳jquery
validate 中文API進行檢視使用。
溫馨提示:本人這裡用的是asp.net開發時使用的,如果我在我的頁面上加上了一個驗證後,頁面上出現兩個按鈕,比如:儲存按鈕,傳回按鈕。如果我們不做處理的話,當單擊兩個按鈕的時候兩個按鈕都會去驗證,導緻傳回按鈕不能傳回。這裡可以在傳回按鈕加上CssClass="cancel",這樣的話當我們點選傳回按鈕的時候就不去驗證了。
比如:
<asp:Button ID="btnSave" runat="server" Text="儲存" Width="85px"
οnclick="btnSave_Click" />
<asp:Button ID="btnBack" runat="server" Text="傳回" Width="85px"
CssClass="cancel" οnclick="btnBack_Click"/>