Recipe 2.1 Requiring that Data be Entered in a Field

     

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

2.1.2 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. Add Save and Cancel (or equivalently named) buttons .

  3. 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 2-1 shows a typical user input form with fields for First Name and Last Name and several other types of information. Figure 2-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 2-1 shows the .aspx file that implements the form, and Example 2-2 and Example 2-3 show the VB and C# code-behind files needed to complete the application.

Figure 2-1. Form with required field validation output ”normal
figs/ancb_0201.gif

Figure 2-2. Form with required field validation output ”with error messages
figs/ancb_0202.gif

2.1.3 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 Figure 2-1 and Figure 2-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 id="rfvFirstName"         Runat="server"  ControlToValidate="txtFirstName"  CssClass="AlertText"        Display="Dynamic"        EnableClientScript="True">      <img src="images/arrow_alert.gif">      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 2.5 for an example that uses an error summary.) In our example, the Display attribute is set to Dynamic so that an error message is issued only when validation fails:

 <asp:RequiredFieldValidator id="rfvFirstName"       Runat="server"      ControlToValidate="txtFirstName"      CssClass="AlertText"  Display="Dynamic"  EnableClientScript="True">    <img src="images/arrow_alert.gif">    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 again 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. In our example, we have set the EnableClientScript attribute to True so that validation is performed on both the client and the server:

 <asp:RequiredFieldValidator id="rfvFirstName"       Runat="server"      ControlToValidate="txtFirstName"      CssClass="AlertText"      Display="Dynamic"  EnableClientScript="True">  <img src="images/arrow_alert.gif">    First Name Is Required </asp:RequiredFieldValidator> 

The error message that is 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 id="rfvFirstName"       Runat="server"      ControlToValidate="txtFirstName"      CssClass="AlertText"      Display="Dynamic"      EnableClientScript="True">  <img src="images/arrow_alert.gif">   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 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:

 <asp:ImageButton id="btnSave" Runat="server"  CausesValidation="True"  ImageUrl="images/buttons/button_save.gif" /> <asp:ImageButton id="btnCancel" Runat="server"  CausesValidation="False"  ImageUrl="images/buttons/button_cancel.gif" /> 

With all the setup done in the .aspx file, the code-behind requires only 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.

2.1.4 See Also

Recipe 2.5

Example 2-1. Form with required field validation (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false"           Codebehind="CH02RequiredFieldValidationVB.aspx.vb"           Inherits="ASPNetCookbook.VBExamples.CH02RequiredFieldValidationVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title>Validator - Required Field</title>     <link rel="stylesheet" href="css/ASPNetCookbook.css">   </head>   <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0">     <form id="frmValidation" method="post" runat="server">       <table width="100%" cellpadding="0" cellspacing="0" border="0">         <tr>           <td align="center">             <img src="images/ASPNETCookbookHeading_blue.gif">           </td>         </tr>         <tr>           <td class="dividerLine">             <img src="images/spacer.gif" height="6" border="0"></td>         </tr>       </table>       <table width="90%" align="center" border="0">         <tr>           <td><img src="images/spacer.gif" height="10" border="0"></td>         </tr>         <tr>           <td align="center" class="PageHeading">             Required Field Validation (VB)           </td>         </tr>         <tr>           <td><img src="images/spacer.gif" height="10" border="0"></td>         </tr>         <tr>           <td align="center">             <table border="0">               <tr>                 <td class="LabelText">First Name: </td>                 <td>                   <asp:TextBox id="txtFirstName" Runat="server"                                 Columns="30" CssClass="LabelText" />  <asp:RequiredFieldValidator id="rfvFirstName"   Runat="server"   ControlToValidate="txtFirstName"   CssClass="AlertText"   Display="Dynamic"   EnableClientScript="True">   <img src="images/arrow_alert.gif">   First Name Is Required   </asp:RequiredFieldValidator>  </td>               </tr>               <tr>                 <td class="LabelText">Last Name: </td>                 <td>                   <asp:TextBox id="txtLastName" Runat="server"                                 Columns="30" CssClass="LabelText" />  <asp:RequiredFieldValidator id="rfvLastName"   Runat="server"   ControlToValidate="txtLastName"   CssClass="AlertText"   Display="Dynamic"   EnableClientScript="True">   <img src="images/arrow_alert.gif">   Last Name Is Required   </asp:RequiredFieldValidator>  </td>               </tr>               <tr>                 <td class="LabelText">Age: </td>                 <td>                   <asp:TextBox id="txtAge" Runat="server"                                 Columns="30" CssClass="LabelText" />                 </td>               </tr>               <tr>                 <td class="LabelText">Country: </td>                 <td>                   <asp:DropDownList id="ddCountry" 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 class="LabelText">Email Address: </td>                 <td>                   <asp:TextBox id="txtEmailAddress" Runat="server"                                 Columns="30" CssClass="LabelText" />                 </td>               </tr>               <tr>                 <td class="LabelText">Password: </td>                 <td>                   <asp:TextBox id="txtPassword1" Runat="server"                                 TextMode="Password"                                 Columns="30" CssClass="LabelText" />                 </td>               </tr>               <tr>                 <td class="LabelText">Re-enter Password: </td>                 <td>                   <asp:TextBox id="txtPassword2" Runat="server"                                 TextMode="Password"                                 Columns="30" CssClass="LabelText" />                 </td>               </tr>               <tr>                 <td colspan="2">                   <br>                   <table align="center" width="50%">                     <tr>                       <td align="center">  <asp:ImageButton id="btnSave" Runat="server"   CausesValidation="True"   ImageUrl="images/buttons/button_save.gif" />  </td>                       <td align="center">  <asp:ImageButton id="btnCancel" Runat="server"   CausesValidation="False"   ImageUrl="images/buttons/button_cancel.gif" />  </td>                     </tr>                   </table>                 </td>               </tr>             </table>           </td>         </tr>       </table>     </form>   </body> </html> 

Example 2-2. Form with required field validation code-behind (.vb)
 Option Explicit On  Option Strict On '----------------------------------------------------------------------------- ' '   Module Name: CH02RequiredFieldValidationVB.aspx.vb ' '   Description: This module provides the code behind for '                CH02RequiredFieldValidationVB.aspx ' '***************************************************************************** Imports System.Web.UI.WebControls Namespace ASPNetCookbook.VBExamples   Public Class CH02RequiredFieldValidationVB     Inherits System.Web.UI.Page     'controls on form     Protected WithEvents btnSave As ImageButton     '***************************************************************************     '     '   ROUTINE: Page_Load     '     '   DESCRIPTION: This routine provides the event handler for the page load     '                event.  It is responsible for initializing the controls     '                on the page.     '---------------------------------------------------------------------------     Private Sub Page_Load(ByVal sender As System.Object, _                           ByVal e As System.EventArgs) _             Handles MyBase.Load       If (Not Page.IsPostBack) Then         'Put user code to initialize the page here       End If     End Sub  'Page_Load     '***************************************************************************     '     '   ROUTINE: btnSave_Click     '     '   DESCRIPTION: This routine provides the event handler for the save      '                button click event.  It is responsible for processing the     '                form data.     '---------------------------------------------------------------------------     Private Sub btnSave_Click(ByVal sender As Object, _                               ByVal e As System.Web.UI.ImageClickEventArgs) _             Handles btnSave.Click  If (Page.IsValid) Then   'process form data and save as required for application   End If  End Sub  'btnSave_Click   End Class  'CH02RequiredFieldValidationVB End Namespace 

Example 2-3. Form with required field validation code-behind (.cs)
 //---------------------------------------------------------------------------- // //   Module Name: CH02RequiredFieldValidationCS.aspx.cs // //   Description: This module provides the code behind for //                CH02RequiredFieldValidationCS.aspx // //**************************************************************************** using System; using System.Web.UI; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples {   public class CH02RequiredFieldValidationCS : System.Web.UI.Page   {     // controls on form     protected ImageButton btnSave;     //************************************************************************     //     //   ROUTINE: Page_Load     //     //   DESCRIPTION: This routine provides the event handler for the page      //                load event.  It is responsible for initializing the      //                controls on the page.     //------------------------------------------------------------------------     private void Page_Load(object sender, System.EventArgs e)     {       // wire the save button click event       this.btnSave.Click += new ImageClickEventHandler(this.btnSave_Click);       if (!Page.IsPostBack)       {         //Put user code to initialize the page here       }     }  // Page_Load     //************************************************************************     //     //   ROUTINE: btnSave_Click     //     //   DESCRIPTION: This routine provides the event handler for the save      //                button click event.  It is responsible for processing      //                the form data.     //------------------------------------------------------------------------     private void btnSave_Click(Object sender,                                System.Web.UI.ImageClickEventArgs e)     {  if (Page.IsValid)   {   // process form data and save as required for application   }  }  // btnSave_Click   }  // CH02RequiredFieldValidationCS } 



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

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