Chapter 8. Validation

As we saw in Chapter 3, many web applications involve user input. The sad fact is, however, that users make mistakes: they skip required fields, they put in six digit phone numbers, and they return all manner of incorrectly formatted data to your application. Your database routines can choke on corrupted data, and orders can be lost if, for example, a credit card number is entered incorrectly or an address is omitted, so it is imperative that user input be validated.

Traditionally, it has taken a great deal of time and effort to validate user input. Each field must be checked and routines must be created for ensuring data integrity. In the event that bad data is found, error messages must be displayed so that the user knows how to correct the problem.

In a given application, you may choose to validate that certain fields have a value, that the values fall within a given range, or that the data is formatted correctly. For example, when processing an order, you may need to ensure that the user has input an address and phone number, that the phone number has the right number of digits (and no letters), and that the social security number entered is in the appropriate form of nine digits separated by hyphens.

Some applications require more complex validation, in which one field is validated to be within a range established by two other fields. For example, you might ask in one field what date the customer wishes to arrive at your hotel, and in a second field you might ask for the departure date. When the user books dinner, you’ll want to ensure that the date is between the arrival and departure dates.

There is no limit to the complexity of the validation routines you may need to write. Credit cards have checksums built into their values, as do ISBN numbers. Zip and postal codes follow complex patterns, as do international phone numbers. You may need to validate passwords, membership numbers, dollar amounts, dates, runway choices, and launch codes.

In addition, it is very desirable for all of this validation to happen client-side so that you avoid the delay of repeated round trips to the server while the user tinkers with his input. In the past, this was solved by writing client-side JavaScript to validate the input, and then server-side script to handle input from browsers that don’t support client-side programming. In addition, as a security check, you may want to do server-side validation even when you already have client-side validation, since it is extremely easy for users to circumvent validation code deliberately. Traditionally, this involved writing your validation code twice.

As you can see, in traditional Internet programming, validation requires extensive custom programming. The ASP.NET framework greatly simplifies this process by providing rich controls for validating user input that provide precise control over the validation routine while requiring far less custom coding. They also allow you to specify exactly how and where the error messages will be displayed; either in-line with the input controls, aggregated together in a summary report, or both. These controls can be used to validate input for both HTML and ASP controls.

You add validation controls to your ASP document just as you would add any other control. Within the declaration of the validation control, you specify which other control is being validated. You may freely combine the various validation controls, and you may write your own, as you’ll see later in this chapter.

With uplevel browsers that support DHTML, such as Internet Explorer 4 or better, .NET validation is done client-side, avoiding the necessity of a round trip to the server. With downlevel browsers your code is unchanged, but the code sent to the client ensures validation at the server. Even when client-side validation is done, the values are validated server-side as well.

The validation is done client side (using DHTML) if the browser will support it; otherwise, the validation is done on the server. Note that even when the validation is done on the client, it is also done on the server as a security precaution.

Because client-side validation will prevent your server-side event handlers from ever running if the control is not valid, you may want to force server-side validation. In that case, set a page attribute:

<%@ Page language="c#" ClientTarget="downlevel"
Codebehind="WebForm1.aspx.cs" 
AutoEventWireup="false" 
Inherits="Validation04.WebForm1" %>

This directive will cause the validation to happen on the server even if your browser would have supported DHTML and client-side validation.

ASP.NET supports the following validation controls:

RequiredFieldValidator control

The simplest validation control, it ensures that the user does not skip over your input control. A RequiredFieldValidator can be tied to a text box to force input into the text box. With selection controls, such as a drop-down or radio buttons, the RequiredFieldValidator ensures that the user makes a selection other than the default. The RequiredFieldValidator does not examine the validity of the data, but only makes sure that some data is entered or chosen.

RangeValidator control

Ensures that the value entered is within a specified lower and upper boundary. You can check the range within a pair of numbers (e.g., greater than 10 and less than 100), a pair of characters (e.g., greater than D and less than K) and a pair of dates (e.g., after 1/1/01 and before 2/28/01). The values you check can be constants that you create at design-time, or they can be derived from other controls on your page (greater than the value in textBox1 and less than the value in textBox2).

CompareValidator control

Compares the user’s entry against another value. It can compare against a constant that you specify at design time, or against a property value of another control. It can also compare against a database value. The comparison must use one of the comparison operators such as less than, equal to, greater than, etc.

RegularExpressionValidator control

One of the most powerful validators, it compares the user’s entry with a regular expression that you provide. You can use this validator to check for valid social security numbers, phone numbers, passwords, and so forth.

CustomValidator control

If none of these controls meets your needs, you can use the CustomValidator. This checks the user’s entry against whatever algorithm you provide in a custom method.

In the remainder of this chapter, we’ll examine how to use each of these controls to validate data in ASP.NET applications.

The RequiredFieldValidator

Let’s start with one of the simpler validators: the RequiredFieldValidator, which ensures that the user provides a valid value for your control. You’ll create the simple bug reporting form shown in Figure 8-1.

The bug report

Figure 8-1. The bug report

When the user presses the Submit Bug button, the form is validated to ensure that each field has been modified. If not, the offending field is marked with a red asterisk, as shown in Figure 8-2. If you prefer more meaningful data reports, you can specify a prompt for each error message, as shown in Figure 8-3. The choice of whether to use an asterisk or a meaningful error message is entirely up to you.

Indicating errors

Figure 8-2. Indicating errors

With error messages

Figure 8-3. With error messages

To create this form, you’ll put the controls inside a simple table, building the drop-down list and button list with items added in the .aspx file.

You start by creating a form. Write the title (which will hold your updated message when the form is validated), and then create the table to hold the controls:

<body>
   <h3>
      <font face="Verdana">Bug Report</font>
   </h3>
   <form runat="server" ID="frmBugs">
      <table bgcolor=gainsboro cellpadding=10>

Next, create the drop-down list in the first cell of the table to hold the book titles:

<td>
<!-- Drop down list with the books (must pick one) -->
   <ASP:DropDownList id=ddlBooks runat=server>
      <asp:ListItem>-- Please Pick A Book --</asp:ListItem>
      <asp:ListItem>Programming ASP.NET</asp:ListItem>

Each title is added and the list is ended:

      <asp:ListItem>Programming C#</asp:ListItem>
      <asp:ListItem>
         Teach Yourself C++ In 21 Days
      </asp:ListItem>
      <asp:ListItem>
         Teach Yourself C++ In 24 Hours
      </asp:ListItem>
      <asp:ListItem>TY C++ In 10 Minutes</asp:ListItem>
      <asp:ListItem>TY More C++ In 21 Days</asp:ListItem>
      <asp:ListItem>C++ Unleashed</asp:ListItem>
      <asp:ListItem>C++ From Scratch</asp:ListItem>
      <asp:ListItem>XML From Scratch</asp:ListItem>
      <asp:ListItem>Web Classes FS</asp:ListItem>
      <asp:ListItem>Beg. OO Analysis & Design</asp:ListItem>
      <asp:ListItem>Clouds To Code</asp:ListItem>
      <asp:ListItem>
         CIG Career Computer Programming
      </asp:ListItem>
   </ASP:DropDownList>
</td>

You then add, in the very next cell, the validator to ensure that a value is selected from the drop-down list:

<!-- Validator for the drop down -->
<td align=middle rowspan=1>
   <asp:RequiredFieldValidator 
   id="reqFieldBooks" 
   ControlToValidate="ddlBooks" 
   Display="Static" 
   InitialValue="-- Please Pick A Book --" 
   Width="100%" runat=server>
      Please choose a book
   </asp:RequiredFieldValidator>
</td>

Notice that the RequiredFieldValidator has an id (reqFieldBooks), and that the value of the next attribute, ControlToValidate , is set to ddlBooks, which is the id of the book drop-down. The Display attribute is set to Static, which tells ASP.NET to allocate room for the validator whether or not there is a message to display. If this is set to Dynamic, space will not be allocated until (and unless) an error message is displayed. Dynamic allocation is very powerful, but it can cause your controls to bounce around on the page when the message is displayed.

In the example, if you set all the validation controls to dynamic no space will be allocated for them, and the browser will decide that your table is only two columns wide rather than three. That is, the table will not allocate any space for the validation messages, and will recognize only one column for the prompt, and the other for the controls. As Figure 8-4 and Figure 8-5 illustrate, when you validate the controls (by pressing the Submit button) the table will widen, which can either be disconcerting or attractive, depending on how you manage the display.

Before pressing Submit

Figure 8-4. Before pressing Submit

After pressing Submit

Figure 8-5. After pressing Submit

The RequiredFieldValidator has an additional attribute, InitialValue , which is set to the initial value of the drop-down box. If the user presses Submit, this initial value will be compared with the value of the drop-down, and if they are the same, the error message will be displayed. This effectively forces the user to change the initial value, picking a particular book to report about.

The form continues with the radio buttons for the edition (1st, 2nd, etc.). These are added in aRadioButtonList, which allows you to programmatically add buttons just like you add items to a drop-down list:

<tr>
   <td align=right>
      <font face=Verdana size=2>Edition:</font>
   </td>
   <td>
      <ASP:RadioButtonList id=rblEdition 
      RepeatLayout="Flow" runat=server>
         <asp:ListItem>1st</asp:ListItem>
         <asp:ListItem>2nd</asp:ListItem>
         <asp:ListItem>3rd</asp:ListItem>
         <asp:ListItem>4th</asp:ListItem>
      </ASP:RadioButtonList>
   </td>

With the buttons in place, you can add the RequiredFieldValidator, which ensures that a button is selected:

<!-- Validator for editions -->
<td align=middle rowspan=1>
   <asp:RequiredFieldValidator 
   id="reqFieldEdition" 
   ControlToValidate="rblEdition" 
   Display="Static" 
   InitialValue="" 
   Width="100%" runat=server>
      Please pick an edition
   </asp:RequiredFieldValidator>
</td>

No need to indicate an initial value this time. Since the control is a radio button list, the validator knows that the user is simply required to pick one of the buttons; if any button is chosen, then the validation is satisfied.

Note

You could vary this example by setting the first button to selected

<asp:ListItem Selected="True">1st</asp:ListItem>

and setting the InitialValue to the text of the first radio button:

<td align=middle rowspan=1>
   <asp: RequiredFieldValidator 
   id="reqFieldEdition" 
   ControlToValidate="rblEdition" 
   Display="Static" 
   InitialValue="1st" 
   Width="100%" runat=server>
      Please pick an edition
   </asp: RequiredFieldValidator>

In this case the form would open with the 1st edition chosen, and the user would be required to pick a different edition.

Finally, to complete the example, add a text box and require that the user enter some text into it. Start by adding the text box itself. The ASP text box control can handle single line (HTML text) or multi-line text boxes (HTML text areas). You’ll ask for a multi-line text area:

<tr>
   <td align=right style="HEIGHT: 97px">
      <font face=Verdana size=2>Bug:</font>
   </td>
   <!-- Multi-line text for the bug entry -->            
   <td style="HEIGHT: 97px">
      <ASP:TextBox id=txtBug runat=server width="183px" 
      textmode="MultiLine" height="68px"/>
   </td>

The validator is straightforward; set the text box as the ControlToValidate and enter the error message to display if the box is left empty:

   <!-- Validator for the text box-->               
   <td style="HEIGHT: 97px">
      <asp:RequiredFieldValidator 
      id="reqFieldBug" 
      ControlToValidate="txtBug" 
      Display="Static" 
      Width="100%" runat=server>
         Please provide bug details
      </asp:RequiredFieldValidator>
   </td>
</tr>

The complete source code is shown in Example 8-1.

Example 8-1. HTML source for the RequiredFieldValidator control example

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" 
AutoEventWireup="false" Inherits="Validation04.WebForm1" %>

<HTML>
  <HEAD>

<!-- Demonstrate simple required field validation -->
      <meta name=vs_targetSchema content="Internet Explorer 5.0">
      <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
      <meta name="CODE_LANGUAGE" Content="C#">
  </HEAD>
   <body>
      <h3>
         <font face="Verdana">Bug Report</font>
      </h3>
      <form runat="server" ID="frmBugs">
         <table bgcolor=gainsboro cellpadding=10>
            <tr valign="top">
               <td colspan=3>
                  <!-- Display error messages -->
                  <asp:Label ID="lblMsg" 
                  Text="Please report your bug here" 
                  ForeColor="red" Font-Name="Verdana" 
                  Font-Size="10" runat=server />
                  <br>
               </td>
            </tr>
            <tr>
               <td align=right>
                  <font face=Verdana size=2>Book</font>
               </td>
               <td>
               <!-- Drop down list with the books (must pick one) -->
                  <ASP:DropDownList id=ddlBooks runat=server>
                     <asp:ListItem>-- Please Pick A Book --</asp:ListItem>
                     <asp:ListItem>Programming ASP.NET</asp:ListItem>
                     <asp:ListItem>Programming C#</asp:ListItem>
                     <asp:ListItem>
                        Teach Yourself C++ In 21 Days
                     </asp:ListItem>
                     <asp:ListItem>
                        Teach Yourself C++ In 24 Hours
                     </asp:ListItem>
                     <asp:ListItem>TY C++ In 10 Minutes</asp:ListItem>
                     <asp:ListItem>TY More C++ In 21 Days</asp:ListItem>
                     <asp:ListItem>C++ Unleashed</asp:ListItem>
                     <asp:ListItem>C++ From Scratch</asp:ListItem>
                     <asp:ListItem>XML From Scratch</asp:ListItem>
                     <asp:ListItem>Web Classes FS</asp:ListItem>
                     <asp:ListItem>Beg. OO Analysis & Design</asp:ListItem>
                     <asp:ListItem>Clouds To Code</asp:ListItem>
                     <asp:ListItem>
                        CIG Career Computer Programming
                     </asp:ListItem>
                  </ASP:DropDownList>
               </td>
               <!-- Validator for the drop down -->
               <td align=middle rowspan=1>
                  <asp:RequiredFieldValidator 
                  id="reqFieldBooks" 
                  ControlToValidate="ddlBooks" 
                  Display="Static" 
                  InitialValue="-- Please Pick A Book --" 
                  Width="100%" runat=server>
                     Please choose a book
                  </asp:RequiredFieldValidator>
               </td>
            </tr>
            <tr>
               <td align=right>
               <!-- Radio buttons for the edition -->                  
                  <font face=Verdana size=2>Edition:</font>
               </td>
               <td>
                  <ASP:RadioButtonList id=rblEdition 
                  RepeatLayout="Flow" runat=server>
                     <asp:ListItem>1st</asp:ListItem>
                     <asp:ListItem>2nd</asp:ListItem>
                     <asp:ListItem>3rd</asp:ListItem>
                     <asp:ListItem>4th</asp:ListItem>
                  </ASP:RadioButtonList>
               </td>
               <!-- Validator for editions -->
               <td align=middle rowspan=1>
                  <asp:RequiredFieldValidator 
                  id="reqFieldEdition" 
                  ControlToValidate="rblEdition" 
                  Display="Static" 
                  InitialValue="" 
                  Width="100%" runat=server>
                     Please pick an edition
                  </asp:RequiredFieldValidator>
               </td>
            </tr>
            <tr>
               <td align=right style="HEIGHT: 97px">
                  <font face=Verdana size=2>Bug:</font>
               </td>
               <!-- Multi-line text for the bug entry -->               
               <td style="HEIGHT: 97px">
                  <ASP:TextBox id=txtBug runat=server width="183px" 
                  textmode="MultiLine" height="68px"/>
               </td>
               <!-- Validator for the text box-->               
               <td style="HEIGHT: 97px">
                  <asp:RequiredFieldValidator 
                  id="reqFieldBug" 
                  ControlToValidate="txtBug" 
                  Display="Static" 
                  Width="100%" runat=server>
                     Please provide bug details
                  </asp:RequiredFieldValidator>
               </td>
            </tr>
            <tr>
               <td>
               </td>
               <td>
                  <ASP:Button id=btnSubmit 
                  text="Submit Bug" runat=server />
               </td>
               <td>
               </td>
            </tr>
         </table>
      </form>
   </body>
</HTML>

The page in Example 8-1 uses a code-behind C# page. The only non-boiler-plate code on that page is the handler for the Submit button, which is shown in Example 8-2.

Example 8-2. Code-behind page for handling the Submit button

protected void btnSubmit_Click(object sender, System.EventArgs e)
{
   if (Page.IsValid == true) 
   {
      lblMsg.Text = "Page is Valid!";
   }
   else 
   {
      lblMsg.Text = "Some of the required fields are empty";
   }
}

Note

To get this code to work on your machine, follow these steps:

  1. Open a new web form application

  2. Copy the HTML code in Example 8-1 over the HTML code, starting at the opening <body> tag.

  3. Switch to design view and look at the form. Double click on the Submit button and paste Example 8-2 over your event handler

  4. Run the application

You can see that btnSubmit_Click is a very simple routine that checks to see if the IsValid flag for the page was set to true, in which case a validating message is displayed in the lblMsg label; otherwise, a warning message is displayed. The IsValid flag is set to true if all the validators report that they are valid.

Tip

Notice that if client-side validation is performed, the warning message will never display. This method only runs on the server, and the page will not be posted to the server if the data is not valid.

The same program in VB.NET looks like this:

Protected Sub btnSubmit_Click( _
  ByVal sender As System.Object, _
  ByVal e As System.EventArgs) _
  Handles btnSubmit.Click

   If Page(  ).IsValid = True Then
      lblMsg(  ).Text = "Page is Valid!"
   Else
      lblMsg(  ).Text = "Some of the required fields are empty"
   End If
End Sub

The .aspx file is unchanged, except that the heading now appears as follows:

<%@ Page Language="vb" AutoEventWireup="false" 
Codebehind="WebForm1.aspx.vb" Inherits="Validation04VB.WebForm1"%>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.101