Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Web Controls: Validation Controls - ASP.NET

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - ASP.NET 2.0 and ASP.NET Ajax

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Web Controls: Validation Controls - ASP.NET

This section introduces a different type of web control, called a validation control (or val-idator), which determines whether the data in another web control is in the proper format.

Validation Controls


This section introduces a different type of web control, called a validation control (or validator), which determines whether the data in another web control is in the proper format. For example, validators could determine whether a user has provided information in a re-quired field or whether a zip-code field contains exactly five digits. Validators provide a mechanism for validating user input on the client. When the XHTML for our page is cre-ated, the validator is converted into JavaScript that performs the validation. However, some clients do not support scripting or disable scripting. So, for security reasons, validation is always performed on the server too—whether or not scripting is enabled on the client. For this example, we assume the client has JavaScript enabled.


Validating Input in a Web Form

The example in this section prompts the user to enter a name, e-mail address and phone number. A website could use a form like this to collect contact information from site vis-itors. After the user enters any data, but before the data is sent to the web server, validators ensure that the user entered a value in each field and that the e-mail address and phone number values are in an acceptable format. In this example, (555) 123-4567, 555-123-4567 and 123-4567 are all considered valid phone numbers. Once the data is submitted, the web server responds by displaying an appropriate message and an XHTML table re-peating the submitted information. Note that a real business application would typically store the submitted data in a database or in a file on the server. We simply send the data back to the form to demonstrate that the server received the data.


Figure 25.17 presents the ASPX file. Like the Web Form in Fig. 25.13, this Web Form uses a table to organize the page’s contents. Lines 24–25, 36–37 and 58–59 define TextBoxes for retrieving the user’s name, e-mail address and phone number, respectively, and line 78 defines a Submit button. Lines 80–82 create a Label named outputLabel that displays the response from the server when the user successfully submits the form. Notice that outputLabel’s Visible property is initially set to False (line 81), so the Label does not appear in the client’s browser when the page loads for the first time.


Using RequiredFieldValidator Controls


In this example, we use three RequiredFieldValidator controls (found in the Validation section of the Toolbox) to ensure that the name, e-mail address and phone number Text-Boxes are not empty when the form is submitted. A RequiredFieldValidator makes an input control a required field. If such a field is empty, validation fails. For example, lines 26–30 define RequiredFieldValidator nameInputValidator, which confirms that nameTextBox is not empty. Line 28 associates nameTextBox with nameInputValidator by setting the validator’s ControlToValidate property to nameTextBox. This indicates that nameInputValidator verifies the nameTextBox’s contents. We set the value of this property (and the validator’s other properties) by selecting the validator in Design mode and using the Properties window to specify property values. Property ErrorMessage’s text (line 29) is displayed on the Web Form if the validation fails. If the user does not input any data in nameTextBox and attempts to submit the form, the ErrorMessage text is displayed in red. Because we set the validator’s Display property to Dynamic (line 28), the validator is displayed on the Web Form only when validation fails. Space is allocated dynamically when validation fails, causing the controls below the validator to shift downward to ac-commodate the ErrorMessage, as seen in Fig. 25.17(a)–(c).


Using RegularExpressionValidator Controls

This example also uses RegularExpressionValidator controls to match the e-mail ad-dress and phone number entered by the user against regular expressions. These controls de-termine whether the e-mail address and phone number were each entered in a valid format.


For example, lines 44–51 create a RegularExpressionValidator named emailFormat-Validator. Line 46 sets property ControlToValidate to emailTextBox to indicate that emailFormatValidator verifies the emailTextBox’s contents.


1    <%-- Fig. 25.17: Validation.aspx --%>


2    <%-- Form that demonstrates using validators to validate user input. --%>


3    <%@ Page Language="VB" AutoEventWireup="false"


4          CodeFile="Validation.aspx.vb" Inherits="Validation" %>


6    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


7          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


9    <html xmlns="http://www.w3.org/1999/xhtml" >


10   <head runat="server">


11           <title>Demonstrating Validation Controls</title>


12   </head>


13   <body>


14         <form id="form1" runat="server">




16   Please fill out the following form.<br /><em>All fields are


17   required and must contain valid information.</em><br />


18   <br />


19   <table>

20   <tr>



21   <td style="width: 100px" valign="top">

22   Name:</td>

23   <td style="width: 450px" valign="top">

24   <asp:TextBox ID="nameTextBox" runat="server">

25   </asp:TextBox><br />

26        <asp:RequiredFieldValidator 

27        ID="nameInputValidator" runat="server"

28        ControlToValidate="nameTextBox" Display="Dynamic"   

29        ErrorMessage="Please enter your name.">   

30        </asp:RequiredFieldValidator>

31   </td>


32   </tr>

33   <tr>



34   <td style="width: 100px" valign="top">E-mail address:</td>

35   <td style="width: 450px" valign="top">

36   <asp:TextBox ID="emailTextBox" runat="server">

37   </asp:TextBox>

38   &nbsp;e.g., user@domain.com<br />

39        <asp:RequiredFieldValidator      

40        ID="emailInputValidator" runat="server"        

41        ControlToValidate="emailTextBox" Display="Dynamic"       

42        ErrorMessage="Please enter your e-mail address.">        

43        </asp:RequiredFieldValidator>        

44        <asp:RegularExpressionValidator  

45        ID="emailFormatValidator" runat="server"  

46        ControlToValidate="emailTextBox" Display="Dynamic"  

47        ErrorMessage=

48        "Please enter an e-mail address in a valid format." 

49        ValidationExpression=  

50        "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

51        </asp:RegularExpressionValidator>

52   </td>


53   </tr>

54   <tr>



55   <td style="width: 100px; height: 21px" valign="top">

56   Phone number:</td>

57   <td style="width: 450px; height: 21px" valign="top">

58   <asp:TextBox ID="phoneTextBox" runat="server">

59   </asp:TextBox>

60   &nbsp;e.g., (555) 555-1234<br />

61        <asp:RequiredFieldValidator      

62        ID="phoneInputValidator" runat="server"        

63        ControlToValidate="phoneTextBox" Display="Dynamic"       

64        ErrorMessage="Please enter your phone number.">     

65        </asp:RequiredFieldValidator>        

66        <asp:RegularExpressionValidator  

67        ID="phoneFormatValidator" runat="server"  

68        ControlToValidate="phoneTextBox" Display="Dynamic"  


69        ErrorMessage=

70        "Please enter a phone number in a valid format."    

71        ValidationExpression=  

72        "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">   


74                            </td>


75                      </tr>


76                </table>


77                <br />


78                <asp:Button ID="submitButton" runat="server" Text="Submit" /><br />


79                <br />


80                <asp:Label ID="outputLabel" runat="server"


81                      Text="Thank you for your submission." Visible="False">


82                </asp:Label>


83         </div>


84         </form>


85   </body>



Fig. 25.17 | Form that demonstrates using validators to validate user input.

A RegularExpressionValidator’s ValidationExpression property specifies the regular expression that validates the ControlToValidate’s contents. Clicking the ellipsis next to property ValidationExpression in the Properties window displays the Regular Expression Editor dialog, which contains a list of Standard expressions for phone numbers, zip codes and other formatted information. You can also write your own custom expression.

For the emailFormatValidator, we selected the standard Internet e-mail  expression address, which uses the validation expression


This regular expression indicates that an e-mail address is valid if the part of the address before the @ symbol contains one or more word characters (i.e., alphanumeric characters or underscores), followed by zero or more strings comprised of a hyphen, plus sign, period or apostrophe and additional word characters. After the @ symbol, a valid e-mail address must contain one or more groups of word characters potentially separated by hyphens or periods, followed by a required period and another group of one or more word characters potentially separated by hyphens or periods. For example, bob.white@email.com, bob-white@my-email.com and bob's-personal.email@white.email.com are all valid e-mail addresses. If the user enters text in the emailTextBox that does not have the correct format and either clicks in a different text box or attempts to submit the form, the ErrorMessage text is displayed in red. You can learn more about regular expressions at  www.regular- expressions.info.


We also use RegularExpressionValidator phoneFormatValidator (lines 66–73) to ensure that the phoneTextBox contains a valid phone number before the form is sub-mitted. In the Regular Expression Editor dialog, we select U.S. phone number, which assigns


((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}


to the ValidationExpression property. This expression indicates that a phone number can contain a three-digit area code either in parentheses and followed by an optional space or without parentheses and followed by required hyphen. After an optional area code, a phone number must contain three digits, a hyphen and another four digits. For example, (555) 123-4567, 555-123-4567 and 123-4567 are all valid phone numbers.


If all five validators are successful (i.e., each TextBox is filled in, and the e-mail address and phone number provided are valid), clicking the Submit button sends the form’s data to the server. As shown in Fig. 25.17(d), the server then responds by displaying the sub-mitted data in the outputLabel (lines 80–82).


Examining the Code-Behind File for a Web Form That Receives User Input


Figure 25.18 depicts the code-behind file for the ASPX file in Fig. 25.17. Notice that this code-behind file does not contain any implementation related to the validators. We say more about this soon.


1    ' Fig. 25.18: Validation.aspx.vb


2    ' Code-behind file for the form demonstrating validation controls.


3    Partial Class Validation


4          Inherits System.Web.UI.Page


6          ' Page_Load event handler executes when the page is loaded


7          Protected Sub Page_Load(ByVal sender As Object, _


8                 ByVal e As System.EventArgs) Handles Me.Load


9                 ' if this is not the first time the page is loading


10               ' (i.e., the user has already submitted form data)


11               If IsPostBack Then


12                      ' retrieve the values submitted by the user


13                      Dim name As String = nameTextBox.Text


Dim email As String = emailTextBox.Text

15   Dim phone As String = phoneTextBox.Text


17   ' create a table indicating the submitted values


18   outputLabel.Text &= _



19   "<br />We received the following  information:" & _

20   "<table style=""background-color: yellow"">" & _

21   "<tr><td>Name: </td><td>" & name  & "</td></tr>" & _

22   "<tr><td>E-mail address: </td><td>"   & email   & "</td></tr>" & _

23   "<tr><td>Phone number: </td><td>" &    phone &   "</td></tr>" & _

24   "<table>"


25   outputLabel.Visible = True ' display the output message


26   End If


27   End Sub ' Page_Load


28   End Class ' Validation


Fig. 25.18 | Code-behind file for the form demonstrating validation controls


Web programmers using ASP.NET often design their web pages so that the current page reloads when the user submits the form; this enables the program to receive input, process it as necessary and display the results in the same page when it is loaded the second time. These pages usually contain a form that, when submitted, sends the values of all the controls to the server and causes the current page to be requested again. This event is known as a postback. Line 11 uses the IsPostBack property of class Page to determine whether the page is being loaded due to a postback. The first time that the web page is requested, IsPostBack is False, and the page displays only the form for user input. When the postback occurs (from the user clicking Submit), IsPostBack is True.


Lines 13–15 retrieve the values of nameTextBox, emailTextBox and phoneTextBox.


When data is posted to the web server, the XHTML form’s data is accessible to the web application through the properties of the ASP.NET controls. Lines 18–24 append to out-putLabel’s Text a line break, an additional message and an XHTML table containing the submitted data, so the user knows that the server received the data correctly. In a real busi-ness application, the data would be stored in a database or file at this point in the applica-tion. Line 25 sets the outputLabel’s Visible property to True, so the user can see the thank you message and submitted data.


Examining the Client-Side XHTML for a Web Form with Validation

Figure 25.19 shows the XHTML and ECMAScript sent to the client browser when Val-idation.aspx loads after the postback. (We added the comments in lines 1–2.) To view this code, select View > Source in Internet Explorer. Lines 27–55, lines 126–190 and lines 196–212 contain the ECMAScript that provides the implementation for the validation controls and for performing the postback. ASP.NET generates this ECMAScript. You do not need to be able to create or even understand ECMAScript—the functionality defined for the controls in our application is converted to working ECMAScript for us.


The EnableViewState attribute determines whether a web control’s value is retained when a postback occurs. Previously, we explicitly set this attribute to False. The default value, True, indicates that the control’s value is retained. In Fig. 25.17(d), notice that the user input is retained after the postback occurs. A hidden input in the XHTML document (lines 17–25 of Fig. 25.19) contains the data of the controls on this page. This element is always named __VIEWSTATE and stores the controls’ data as an encoded string.


1    <!-- Fig. 25.19 -->


2    <!-- The XHTML and ECMAScript generated for Validation.aspx -->


3    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


4          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


5    <html xmlns="http://www.w3.org/1999/xhtml" >


6    <head>


7    <title>Demonstrating Validation Controls</title>


8    </head>


9    <body>


10   <form name="form1" method="post" action="Validation.aspx"


11         onsubmit="javascript:return WebForm_OnSubmit();" id="form1">


12         <div>


13               <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET"


14                      value="" />


15               <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT"


16                      value="" />


17               <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"


18                      value="/wEPDwUJMzg4NDI1NzgzD2QWAgIDD2QWAgITDw8WBB4EVGV4dAWVAlRoY


19                      W5rIHlvdSBmb3IgeW91ciBzdWJtaXNzaW9uLjxiciAvPldlIHJlY2VpdmVkIHRoZ


20                      SBmb2xsb3dpbmcgaW5mb3JtYXRpb246PHRhYmxlIHN0eWxlPSJiYWNrZ3JvdW5kL


21                      WNvbG9yOiB5ZWxsb3ciPjx0cj48dGQ+TmFtZTogPC90ZD48dGQ+Qm9iIFdoaXRlP


22                        C90ZD48L3RyPjx0cj48dGQ+RS1tYWlsIGFkZHJlc3M6IDwvdGQ+PHRkPmJ3aGl0


23                      ZUBlbWFpbC5jb208L3RkPjwvdHI+PHRyPjx0ZD5QaG9uZSBudW1iZXI6IDwvdGQ+


24                      PHRkPig1NTUpIDU1NS0xMjM0PC90ZD48L3RyPjx0YWJsZT4eB1Zpc2libGVnZGRk


25                      qbjgKg1/lLZfogqihtkd1C7nmSk=" />


26         </div>


27         <script type="text/javascript">

28         <!--


29         var theForm = document.forms['form1'];


30         if (!theForm) {


31               theForm = document.form1;

32         }


33         function __doPostBack(eventTarget, eventArgument) {


34               if (!theForm.onsubmit || (theForm.onsubmit() != false)) {


35                      theForm.__EVENTTARGET.value = eventTarget;


36                      theForm.__EVENTARGUMENT.value = eventArgument;


37                      theForm.submit();

38               }

39         }

40         // -->


41         </script>


42         <script src="/Validation/WebResource.axd?d=g4BXOwpt2-0jwFwNi7BCNQ2


43               &amp;t=632670465355304640" type="text/javascript"></script>


44          <script src="/Validation/WebResource.axd?d=ZlFGPYdc0paOPqraRf9s2PN8QeuH


45               PzQxnkR5mPVtAVc1&amp;t=632670465355304640"


46               type="text/javascript"></script>


47         <script type="text/javascript">

48         <!--


49         function WebForm_OnSubmit() {


50               if (typeof(ValidatorOnSubmit) == "function" &&


ValidatorOnSubmit() == false) return false;

52                return true;

53         }

54         // -->


55         </script>


56         <div>


57                Please fill out the following form.<br />


58                <em>All fields are required and must contain valid information.


59                </em><br />


60                <br />


61                <table>


63   <td style="width: 100px" valign="top"> Name:</td>

64   <td style="width: 450px" valign="top">

65   <input name="nameTextBox" type="text" value="Bob White"

66   id="nameTextBox" />

67   <br />

68   <span id="nameInputValidator"

69   style="color:Red;display:none;">

70   Please enter your name.</span> </td>

71   </tr>

72   <tr>



73   <td style="width: 100px" valign="top">E-mail address:</td>

74   <td style="width: 450px" valign="top">

75   <input name="emailTextBox" type="text"

76   value="bwhite@email.com" id="emailTextBox" />

77   &nbsp;e.g., user@domain.com<br />

78   <span id="emailInputValidator"

79   style="color:Red;display:none;">

80   Please enter your e-mail address.</span>

81   <span id="emailFormatValidator"

82   style="color:Red;display:none;">Please enter an e-mail

83   address in a valid format.</span> </td>

84   </tr>

85   <tr>



86   <td style="width: 100px; height: 21px" valign="top">

87   Phone number:</td>

88   <td style="width: 450px; height: 21px" valign="top">

89   <input name="phoneTextBox" type="text"

90   value="(555) 555-1234" id="phoneTextBox" />

91   &nbsp;e.g., (555) 555-1234<br />

92   <span id="phoneInputValidator"

93   style="color:Red;display:none;">

94   Please enter your phone number.</span>

95   <span id="phoneFormatValidator"

96   style="color:Red;display:none;">Please enter a phone

97   number in a valid format.</span> </td>

98   </tr>


99   </table>

100  <br />


101  <input type="submit" name="submitButton" value="Submit"


102  onclick="javascript:WebForm_DoPostBackWithOptions(

103  new WebForm_PostBackOptions(&quot;submitButton&quot;,

104  &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false,

105  false))" id="submitButton" />

106  <br />

107  <br />


108  <span id="outputLabel">Thank you for your submission.<br />


109  We received the following information:


110  <table style="background-color: yellow">

111  <tr>



112  <td>Name: </td>

113  <td>Bob White</td>

114  </tr>

115  <tr>



116  <td>E-mail address: </td>

117  <td>bwhite@email.com</td>

118  </tr>

119  <tr>



120  <td>Phone number: </td>

121  <td>(555) 555-1234</td>

122                         </tr>


123                   <table>


124             </span>

125      </div>


126      <script type="text/javascript">

127      <!--


128             var Page_Validators = new Array(


129                   document.getElementById("nameInputValidator"),


130                   document.getElementById("emailInputValidator"),


131                   document.getElementById("emailFormatValidator"),


132                   document.getElementById("phoneInputValidator"),


133                   document.getElementById("phoneFormatValidator"));

134      // -->


135      </script>


136      <script type="text/javascript">

137      <!--


138             var nameInputValidator = document.all ?


139                   document.all["nameInputValidator"] :


140                   document.getElementById("nameInputValidator");


141             nameInputValidator.controltovalidate = "nameTextBox";


142             nameInputValidator.errormessage = "Please enter your name.";


143             nameInputValidator.display = "Dynamic";


144             nameInputValidator.evaluationfunction =


145                   "RequiredFieldValidatorEvaluateIsValid";


146             nameInputValidator.initialvalue = "";


147             var emailInputValidator = document.all ?


148                   document.all["emailInputValidator"] :


149                   document.getElementById("emailInputValidator");


150             emailInputValidator.controltovalidate = "emailTextBox";


151             emailInputValidator.errormessage =


152                   "Please enter your e-mail address.";


emailInputValidator.display = "Dynamic";

154             emailInputValidator.evaluationfunction =


155                   "RequiredFieldValidatorEvaluateIsValid";


156             emailInputValidator.initialvalue = "";


157             var emailFormatValidator = document.all ?


158                   document.all["emailFormatValidator"] :


159                   document.getElementById("emailFormatValidator");


160             emailFormatValidator.controltovalidate = "emailTextBox";


161             emailFormatValidator.errormessage =


162                   "Please enter an e-mail address in a valid format.";


163             emailFormatValidator.display = "Dynamic";


164             emailFormatValidator.evaluationfunction =


165                   "RegularExpressionValidatorEvaluateIsValid";


166             emailFormatValidator.validationexpression =


167                   "\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";


168             var phoneInputValidator = document.all ?


169                   document.all["phoneInputValidator"] :


170                   document.getElementById("phoneInputValidator");


171             phoneInputValidator.controltovalidate = "phoneTextBox";


172             phoneInputValidator.errormessage =


173                   "Please enter your phone number.";


174             phoneInputValidator.display = "Dynamic";


175             phoneInputValidator.evaluationfunction =


176                   "RequiredFieldValidatorEvaluateIsValid";


177             phoneInputValidator.initialvalue = "";


178             var phoneFormatValidator = document.all ?


179                   document.all["phoneFormatValidator"] :


180                   document.getElementById("phoneFormatValidator");


181             phoneFormatValidator.controltovalidate = "phoneTextBox";


182             phoneFormatValidator.errormessage =


183                   "Please enter a phone number in a valid format.";


184             phoneFormatValidator.display = "Dynamic";


185             phoneFormatValidator.evaluationfunction =


186                   "RegularExpressionValidatorEvaluateIsValid";


187             phoneFormatValidator.validationexpression =


188                   "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}";

189      // -->


190      </script>

191      <div>


192           <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"


193                     value="/wEWBQL6jZCbCAKLsYSOBwKCkfPgDAKE8IO1CQKSuuDUC0eNO370TaQqZQ


194                         0WPApD0KktGC5N" />

195      </div>


196      <script type="text/javascript">

197      <!--


198             var Page_ValidationActive = false;


199             if (typeof(ValidatorOnLoad) == "function") {


200                     ValidatorOnLoad();

201             }


203             function ValidatorOnSubmit() {


if (Page_ValidationActive) {


205                         return ValidatorCommonOnSubmit();

206                   }

207                   else {


208                       return true;

209                   }

210             }

211      // -->


212      </script>


213    </form>


214    </body>


215    </html>


Fig. 25.19 | XHTML and ECMAScript generated by ASP.NET and sent to the browser when

Validation.aspx is requested.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.