Recipe 3.2. Requiring That Data Be Entered in a Field


Problem

You need to ensure that a user has entered data in a text box, such as a first or last name on a registration form.

Solution

Add a RequiredFieldValidator control to the .aspx file, and use the event handler of the control that completes the user's entry for the page to verify that validation was successful.

In the .aspx file:

  1. Add a RequiredFieldValidator control for each text box in which data must be entered.

  2. Set the ControlToValidate attribute to the ID of the control to validate.

  3. Add Save and Cancel (or equivalently named) buttons.

  4. Set the Save button's CausesValidation attribute to true to have validation performed when the button is clicked (set it to False for the Cancel button).

In the code-behind class, use the .NET language of your choice to add code to the event handler for the Save button's click event that checks the Page.IsValid property and verifies that all validation was successful.

Figure 3-1 shows a typical user input form with fields for First Name and Last Name and several other types of information. Figure 3-2 shows the same form with validation error messages that appear when the user fails to complete the First Name and Last Name fields. Example 3-1 shows the .aspx file that implements the form, and Examples 3-2 and 3-3 show the VB and C# code-behind files needed to complete the application.

Figure 3-1. Form with required field validation outputnormal


Figure 3-2. Form with required field validation outputwith error messages


Discussion

When you need to insist that a user enter data into a text box, a common requirement for forms used to register new users for a site or service, the RequiredFieldValidator control provides a straightforward way to enforce the rule. We've used the control to require completion of the First Name and Last Name text boxes of a simple registration form (see Figures 3-1 and Figures 3-2). You need to assign a RequiredFieldValidator control to each text box you wish to check. Each validator control must be placed on the form at the exact spot where you want its error message to be displayed (typically just after the text box it validates), and the ControlToValidate attribute of the validator must be set to the ID of the text box as shown in the following code snippet. In our example, the names of the First Name and Last Name text boxes are txtFirstName and txtLastName, respectively.

 <asp:RequiredFieldValidator   Runat="server"  ControlToValidate="txtFirstName"  Css  Display="Dynamic"  EnableClientScript="True">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    First Name Is Required </asp:RequiredFieldValidator> 

The Display attribute must be set to Dynamic, Static, or None. Dynamic causes ASP.NET to output the HTML related to the validator error message only when an error message is to be output. Static causes HTML related to the validator error message to be output at all times even when an error message is not output. None prevents any HTML related to the validator error message from being output; this setting is useful when you plan to use an error summary and do not wish to display an error message at the specific field. (See Recipe 3.5 for an example that uses an error summary.) In our example, the Display attribute is set to Dynamic so an error message is issued only when validation fails:

 <asp:RequiredFieldValidator   Runat="server"  ControlToValidate="txtFirstName"  Css  Display="Dynamic"  EnableClientScript="True">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    First Name Is Required </asp:RequiredFieldValidator> 

The EnableClientScript attribute can be set to true or False as a function of how you want validation performed. Setting the attribute to TRue causes validation to be performed on the client and on the server when the form is submitted. Setting the attribute to False causes validation to be performed only on the server when the form is submitted. See Recipe 3.6 for an example showing when you may want to set this attribute to False. In our example, we have set the EnableClientScript attribute to true so validation is performed on the client and the server:

 <asp:RequiredFieldValidator   Runat="server"      ControlToValidate="txtFirstName"  Css  Display="Dynamic"  EnableClientScript="True">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    First Name Is Required </asp:RequiredFieldValidator> 

The error message to be output when validation fails is placed between the open and close tags of the control. The message can include HTML, as shown here, where an HTML image tag comes first, followed by text:

 <asp:RequiredFieldValidator   Runat="server"  ControlToValidate="txtFirstName"  Css  Display="Dynamic"  EnableClientScript="True">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    First Name Is Required </asp:RequiredFieldValidator> 

In our application, two buttons are provided on the form to allow the user to submit or cancel the page. The Save button causes the form to be submitted and the data the user has entered to be validated, while the Cancel button causes validation to be bypassed. Validation is requested by setting the CausesValidation attribute to true for the Save button and False for the Cancel button:

 <input  runat="server" type="button"   value="Save" causesvalidation="true"   onserverclick="btnSave_ServerClick"/> <input  runat="server" type="button"   value="Cancel" causesvalidation="false"/> 

With the setup done in the .aspx file, the code-behind requires a simple check of the Page.IsValid property in the event handler for the Save button's click event. This is done to ensure all client-and server-side validation was successful before processing the form data.

See Also

Recipes 3.5 and 3.6

Example 3-1. Form with required field validation (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"  AutoEventWireup="false"      CodeFile="CH03RequiredFieldValidationVB.aspx.vb"      Inherits="ASPNetCookbook.VBExamples.CH03RequiredFieldValidationVB"      title="Validator - Required Field" %> <asp:Content  Runat="server" ContentPlaceHolder>    <div align="center" >      Required Field Validation (VB)    </div>    <table align="center" ></tr> <td >First Name: </td>         <td>           <asp:TextBox  Runat="server"                      Columns="30" Css />   <asp:RequiredFieldValidator     Runat="server"    ControlToValidate="txtFirstName"    Css    Display="Dynamic"    EnableClientScript="True">      <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>  First Name Is Required   </asp:RequiredFieldValidator>     </td>      </tr>      </tr> <td >Last Name: </td> <td>   <asp:TextBox  Runat="server"  Columns="30" Css />   <asp:RequiredFieldValidator     Runat="server"    ControlToValidate="txtLastName"    Css    Display="Dynamic"    EnableClientScript="True"> <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> Last Name Is Required      </asp:RequiredFieldValidator>    </td>      </tr>  </tr>    <td >Age: </td>    <td>    <asp:TextBox  Runat="server"  Columns="30" Css />    </td>      </tr>      </tr>    <td >Country: </td>    <td>    <asp:DropDownList  Runat="server" >         <asp:ListItem Selected="True" Value="0">----- Select Country -----</asp:ListItem>     <asp:ListItem Value="1">Canada</asp:ListItem>     <asp:ListItem Value="2">United States</asp:ListItem>        </asp:DropDownList>        </td>      </tr>      </tr>     <td >Email Address: </td>     <td>     <asp:TextBox  Runat="server" Columns="30" Css />   </td> </tr> </tr>      <td >Password: </td>      <td>     <asp:TextBox  Runat="server" TextMode="Password" Columns="30" Css />   </td>     </tr>     </tr> <td >Re-enter Password: </td> <td>     <asp:TextBox  Runat="server" TextMode="Password" Columns="30" Css />   </td>     </tr>     </tr> <td colspan="2">     <br/>     <table align="center" width="50%"></tr>    <td align="center">   <input  runat="server" type="button" value="Save" causesvalidation="true" onserverclick="btnSave_ServerClick"/>     </td>     <td align="center">        <input  runat="server" type="button" value="Cancel" causesvalidation="false" onserverclick="btnCancel_ServerClick" />      </td>    </tr> </table> </td> </tr>   </table> </asp:Content> 

Example 3-2. Form with required field validation code-behind (.vb)

 Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples   ''' <summary>   ''' This class provides the code behind for CH03RequiredFieldValidationVB.aspx   ''' </summary>   Partial Class CH03RequiredFieldValidationVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the save button click ''' event. It is responsible for processing the form data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnSave_ServerClick(ByVal sender As Object, _   ByVal e As System.EventArgs)     If (Page.IsValid) Then  'process form data and save as required for application    End If End Sub 'btnSave_ServerClick '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the cancel button click ''' event. It is responsible for processing the form data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnCancel_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs)   'perform any cancel operations required for application End Sub 'btnCancel_ServerClick   End Class 'CH03RequiredFieldValidationVB End Namespace 

Example 3-3. Form with required field validation code-behind (.cs)

 using System; namespace ASPNetCookbook.CSExamples {   /// <summary>   /// This class provides the code behind for   /// CH03RequiredFieldValidationCS.aspx   /// </summary>   public partial class CH03RequiredFieldValidationCS : System.Web.UI.Page   { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the save button click /// event. It is responsible for processing the form data. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnSave_ServerClick(Object sender,    System.EventArgs e) {   if (Page.IsValid)   { // process form data and save as required for application   } } //btnSave_ServerClick ///*********************************************************************** /// <summary> /// This routine provides the event handler for the cancel button click /// event. It is responsible for processing the form data. /// </summary> /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnCancel_ServerClick(Object sender, System.EventArgs e) {   // perform any cancel operations required for application }  // btnCancel_ServerClick   } // CH03RequiredFieldValidationCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

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