Section 8.1. The RequiredFieldValidator

8.1. The RequiredFieldValidator

The RequiredFieldValidator , ensures the user provides a valid value for your control.

To get started, create a new web site called RequiredFieldValidator. You'll create the bug reporting web page shown in Design view in Figure 8-1.

Figure 8-1. Validator bug report in the designer

When the user clicks the Submit Bug button, the page is validated to ensure each field has been modified. If not, the offending field is marked with an error message in red, as shown in Figure 8-2.

Figure 8-2. Required field validation errors reported when page is submitted

The complete source code for the content file, default.aspx , for this example is shown in Example 8-1.

Example 8-1. default.aspx for the RequiredFieldValidator example
 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs"          Inherits="Default_aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>Required Field Validation</title> </head> <body>     <h3>         <font face="Verdana">Bug Report</font>     </h3>     <form runat="server" ID="frmBugs">         <div>          <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-Names="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 .NET Windows Applications                      </asp:ListItem>                      <asp:ListItem>Programming C#</asp:ListItem>                      <asp:ListItem>                           Programming Visual Basic 2005                      </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:DropDownList>                </td>                <!-- Validator for the drop down -->                <td align=center 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=center 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>     </div>     </form> </body> </html> 

To lay out this page, you'll put the controls inside an HTML table. For each field that you want validated, however, you'll add a RequiredFieldValidator control, (which is a control like any other).

The RequiredFieldValidator control has its own ID , and it also asks for the ID of the control you wish to validate. Thus, the first RequiredFieldValidator you'll add will have the ID of reqFieldBooks , but its ControlToValidate property will be set to ddlBooks (the drop-down list that you are validating):

 <asp:RequiredFieldValidator runat=server  id="reqFieldBooks"    ControlToValidate="ddlBooks"  Display="Static"    InitialValue="-- Please Pick A Book --"    Width="100%" >    Please choose a book </asp:RequiredFieldValidator> 

The Display attribute is set to Static , which tells ASP.NET to allocate room on the page 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 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. When you validate the controls (by clicking the Submit button), the table will widen, which can be disconcerting or attractive depending on how you manage the display.

The RequiredFieldValidator has an additional attribute, InitialValue , which is set to the initial value of the drop-down box. If the user clicks 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 forces the user to change the initial value, picking a particular book to report.

The second RequiredFieldValidator ensures that one of the radio buttons in rblEdition is selected:

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

You do not need to indicate an initial value this time. Since the control is a radio button list, the validator knows the user is required to pick one of the buttons; if any button is chosen , the validation will be satisfied.

Finally, to complete the example, add a text box and require the user to enter some text in it. 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 runat=server          id="reqFieldBug"          ControlToValidate="txtBug"          Display="Static"          Width="100%" >          Please provide bug details       </asp:RequiredFieldValidator>    </td> </tr> 

The only code required in the code-behind file is the event handler for the Submit button:

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

When the Submit button is clicked, the page is posted to the server. The validation for each control is checked, and if every control is valid, the IsValid property of the page will return true .

You can make your pages a bit friendlier for your users by placing the focus on the first control that fails validation. To do so, add the SetFocusOnError property to each validation control and set it to true (the default is false ):

 <asp:RequiredFieldValidator runat=server    id="reqFieldBug"    ControlToValidate="txtBug"    Display="Static"  SetFocusOnError=true  Width="100%" >    Please provide bug details </asp:RequiredFieldValidator> 

When one or more controls uses SetFocusOnError and if the page is invalid, the focus will be set to the first control that fails validation and has this property set to true .



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

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