天天看點

asp.net的驗證控件引言:分類:使用:總結:

引言:

    以前判斷控件是否為空、是否符合格式、是否在某個範圍、比較兩個字段……都是在代碼裡寫的,學到asp.net時發現驗證控件可以做到,友善了很多,其實之前我們也經常見到,在注冊或填寫某些資訊時,框右邊有*,如果輸入錯誤就會提示,這就是所謂的驗證控件。

分類:

asp.net的驗證控件引言:分類:使用:總結:

使用:

   在vs的工具箱中:

asp.net的驗證控件引言:分類:使用:總結:

 Demo1:

asp.net的驗證控件引言:分類:使用:總結:

 RequiredFieldValidator:(判斷文本框的輸入是否為空)  

 在文本框的後邊拖一個RequiredFieldValidator控件,然後修改其屬性:

asp.net的驗證控件引言:分類:使用:總結:

ControlToValidate 是指定對那個控件的驗證;

ErrorMessage是對錯誤的提示資訊内容;

Text是以什麼形式顯示;

前台代碼:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtUserName" Display="Dynamic" ErrorMessage="使用者名必填">*</asp:RequiredFieldValidator>
           

CompareValidator:(比較兩個字段)

 以上面的密碼和确認密碼為例:

 添加控件後修改其屬性:

asp.net的驗證控件引言:分類:使用:總結:

ControlToValidate 是指定對那個控件的驗證;

ControlToCompare:跟那個控件進行比較;

ErrorMessage:錯誤提示資訊;

Operator:比較關系,equal判斷是否相等

Text:顯示内容

代碼:

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtUserPwd" ControlToValidate="txtUserPwdAgain" Display="Dynamic" ErrorMessage="兩次輸入的密碼不一緻" ForeColor="#CC0000">*</asp:CompareValidator>
           

CustomValidator:(通過用戶端或服務端函數檢查值)

 以檢查使用者名是否存在為例:

asp.net的驗證控件引言:分類:使用:總結:

代碼:

<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txtUserName" ErrorMessage="使用者名已經存在" OnServerValidate="CustomValidator2_ServerValidate" Display="Dynamic" ForeColor="Red">*</asp:CustomValidator>
           

這個控件觸發了服務驗證

OnServerValidate="CustomValidator2_ServerValidate"
           

ValidationSummary:(收集驗證錯誤資訊)

    該控件不對Web窗體中輸入的資料進行驗證,而是收集本頁的所有驗證錯誤資訊,并可以将它們組織以後再顯示出來。這個控件會将頁面中所有的校驗錯誤輸出為一個清單,清單的顯示方式由DisplayMode屬性設定。

其标準代碼如下:

<asp:ValidationSummary ID="Validator_ID" runat="Server" HeaderText="頭資訊" ShowSummary="True|False" DiaplayMode="List|BulletList|SingleParagraph" />
           

HeadText相當于表的HeadText;

DisplayMode表示錯誤資訊顯示方式;

List相當于HTML中的<BR>;BulletList相當于HTML中的<LI>;

SingleParegraph表示錯誤資訊之間不作如何分割。

如下代碼,将錯誤資訊顯示在一個對話框中。

<asp:ValidationSummary ID="Validator_ID" runat="Server" HeaderText="ValidationSummaryName" ShowSummary="False" ShowMessageBox="True" />
           

運作結果展示:

asp.net的驗證控件引言:分類:使用:總結:
asp.net的驗證控件引言:分類:使用:總結:

RangeValidator:(指定範圍)

Demo2:

asp.net的驗證控件引言:分類:使用:總結:

以出生日期為例講述

asp.net的驗證控件引言:分類:使用:總結:

代碼:

<asp:RangeValidator ID="RangeValidator1" runat="server" Display="Dynamic" ErrorMessage="生日超出範圍" ForeColor="#CC0000" MaximumValue="2000-1-1" MinimumValue="1980-1-1" ControlToValidate="txtBirth">*</asp:RangeValidator>
           

RegularExpressionValidator:(使用表達式檢值)

Demo3:

asp.net的驗證控件引言:分類:使用:總結:
asp.net的驗證控件引言:分類:使用:總結:

正規表達式編輯器中有我們常用的格式(郵箱、身份證号、電話号、郵政編碼...)

運作結果:

asp.net的驗證控件引言:分類:使用:總結:

總結:

        站在巨人的肩膀上