8.1 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.

Figure 8-1. The bug report
figs/pan2_0801.gif

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.

Figure 8-2. Indicating errors
figs/pan2_0802.gif
Figure 8-3. With error messages
figs/pan2_0803.gif

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" >       <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          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.

Figure 8-4. Before pressing Submit
figs/pan2_0804.gif
Figure 8-5. After pressing Submit
figs/pan2_0805.gif

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 a RadioButtonList, 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          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.

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          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                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" >          <table bgcolor=gainsboro cellpadding=10>             <tr valign="top">                <td colspan=3>                   <!-- Display error messages -->                   <asp:Label                     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                                        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                                        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                                        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>

If you are using VB.NET then your page directive would look like this:

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

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. -2. C# Code-behind for handling the Submit button
protected void btnSubmit_Click(object sender, System.EventArgs e) {    if (Page.IsValid)     {       lblMsg.Text = "Page is Valid!";    }    else     {       lblMsg.Text = "Some of the required fields are empty";    } }

The VB.NET version of the code is shown in Example 8-3.

Example 8-3. -3. VB.NET Code-behind page for handling the Submit button
protected sub btnSubmit_Click(sender As Object, e As System.EventArgs)_    if Page.IsValid then       lblMsg.Text = "Page is Valid!"    else        lblMsg.Text = "Some of the required fields are empty"    end if end sub

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 to a new web form in Visual Studio .NET, starting at the opening <body> tag. Do not copy the page directive portion, because your file, class, and namespace names will probably differ.

  3. Switch to design view and look at the form. Double click on the Submit button and paste the C# code from Example 8-2, or the VB.NET code from Example 8-3 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.

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.



Programming ASP. NET
Programming ASP.NET 3.5
ISBN: 0596529562
EAN: 2147483647
Year: 2003
Pages: 156

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net