ASP.NET數(shù)據(jù)驗證中的驗證組淺析
ASP.NET數(shù)據(jù)驗證中的驗證組是什么概念呢?讓我們開始講述:
ASP.NET數(shù)據(jù)驗證是為了防止用戶錄入錯誤數(shù)據(jù)或者漏掉必須填寫的數(shù)據(jù)而使得服務器出現(xiàn)不必要的錯誤,ASP.NET有驗證控件方便我們進行數(shù)據(jù)驗證,但是有時會出現(xiàn)這樣或者那樣的問題,我今天就遇到了一個,把驗證控件說一下吧
- ﹤asp:TextBox ID="TextBox1" runat="server"﹥﹤/asp:TextBox﹥
- ﹤asp:RequiredFieldValidator ID="RequiredFieldValidator1"
- ControlToValidate="TextBox1" runat="server" ErrorMessage="RequiredFieldValidator"﹥
- ﹤/asp:RequiredFieldValidator﹥
- ﹤asp:Button ID="Button1" runat="server" Text="Button1" /﹥
上面的ASP.NET數(shù)據(jù)驗證代碼實現(xiàn)了最基本的驗證,用戶如果不輸入信息而直接點擊Button1那么ErrorMessage就會顯示出來
- ﹤asp:TextBox ID="TextBox1" runat="server"﹥﹤/asp:TextBox﹥
- ﹤asp:RequiredFieldValidator ID="RequiredFieldValidator1"
- ControlToValidate="TextBox1" runat="server" ErrorMessage="RequiredFieldValidator"﹥
- ﹤/asp:RequiredFieldValidator﹥
- ﹤asp:Button ID="Button1" runat="server" Text="Button1" /﹥
- ﹤asp:Button ID="Button2" runat="server" Text="Button2" /﹥
在上面的ASP.NET數(shù)據(jù)驗證代碼中用戶如果不輸入信息而點擊Button1或者Button2那么ErrorMessage都會顯示出來.如果我不想讓Button2引發(fā)驗證怎么辦呢? 好辦,給Button2添加一個屬性 CausesValidation="false" 如下
- ﹤asp:TextBox ID="TextBox1" runat="server"﹥﹤/asp:TextBox﹥
- ﹤asp:RequiredFieldValidator ID="RequiredFieldValidator1"
- ControlToValidate="TextBox1" runat="server" ErrorMessage="RequiredFieldValidator"﹥
- ﹤/asp:RequiredFieldValidator﹥
- ﹤asp:Button ID="Button1" runat="server" Text="Button1" /﹥
- ﹤asp:Button ID="Button2" runat="server" Text="Button2" CausesValidation="false" /﹥
這樣用戶如果在不輸入信息的情況下直接點擊Button2 ErrorMessage就不會出現(xiàn)
但是有時候需要我們在同一頁面驗證不同的信息,你肯定不能將按鈕的 CausesValidation="false" 加上,我們需要加的是ValidationGroup屬性
- ﹤asp:TextBox ID="TextBox1" runat="server"﹥﹤/asp:TextBox﹥
- ﹤asp:RequiredFieldValidator ID="RequiredFieldValidator1"
- ControlToValidate="TextBox1" ValidationGroup="basicInfo" runat="server" ErrorMessage="error form textbox1"﹥
- ﹤/asp:RequiredFieldValidator﹥
- ﹤asp:Button ID="Button1" ValidationGroup="basicInfo" runat="server" Text="Button1" /﹥
- ﹤asp:TextBox ID="TextBox2" runat="server"﹥﹤/asp:TextBox﹥
- ﹤asp:RequiredFieldValidator ID="RequiredFieldValidator2"
- ControlToValidate="TextBox2" ValidationGroup="moreInof" runat="server" ErrorMessage="error form textbox2" ﹥
- ﹤/asp:RequiredFieldValidator﹥
- ﹤asp:Button ID="Button2" ValidationGroup="moreInof" runat="server" Text="Button2" /﹥
這樣就實現(xiàn)了你點擊Button只引發(fā)對特定button的ASP.NET數(shù)據(jù)驗證而不會影響其他的button
總結:使用ASP.NET數(shù)據(jù)驗證驗證組可以將頁面上的驗證控件歸為一組。可以對每個驗證組執(zhí)行驗證,該驗證與同一頁的其他驗證組無關。
將要分組的所有控件的 ValidationGroup 屬性設置為同一個名稱(字符串)即可創(chuàng)建驗證組。可以為驗證組分配任何名稱,但必須對該組的所有成員使用相同的名稱。
ASP.NET數(shù)據(jù)驗證中驗證組的相關信息就向你介紹到這里,希望對你理解ASP.NET數(shù)據(jù)驗證中的驗證組有所幫助。
【編輯推薦】