Recipe 3.6. Requiring That a Drop-Down List Selection Be Made


Problem

You need to make sure a user selects an entry in a drop-down list.

Solution

Add a CustomValidator control to the drop-down list, along with some client-side JavaScript to validate the selection. Next, implement an event handler for the CustomValidator control's ServerValidate event. Finally, check the Page.IsValid property in the event handler for the control that completes the user's entry for the page.

In the .aspx file:

  1. Add a CustomValidator control for each drop-down list where you must verify that an item has been selected.

  2. Add JavaScript to validate the selection on the client side.

  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 for the page, use the .NET language of your choice to:

  1. Add an event handler for the CustomValidator control's ServerValidate event whose purpose is to provide the server-side validation to ensure an item has been selected.

  2. Add code to the event handler for the Save button's click event to check the Page.IsValid property and verify that all validation was successful (see Recipe 3.1 for details).

Figure 3-10 shows a typical form with normal output prior to data entry. Figure 3-11 shows the form with validation errors. Examples 3-7, 3-8 through 3-9 show the .aspx and code-behind files for our application that implements the solution.

Figure 3-10. Form with selection validation outputnormal


Discussion

This recipe involves using a CustomValidator control to verify that an item has been selected in a drop-down list. But the approach we advocate is out of the ordinary for a couple of reasons. First, by implementing validation via client-side JavaScript, errors can be detected on the client, thus avoiding unnecessary round trips to the server for server-side validation.

Figure 3-11. Form with selection validation outputwith error summary


Besides using a CustomValidator control, this application uses validation controls from all of the previous recipes combined, specifically RequiredFieldValidator, RangeValidator, CompareValidator, and RegularExpressionValidator. Combining validators of various types is typical when performing validation on a complex form.


Second, instead of displaying an error message at each control, this example shows how to use a ValidationSummary control to provide a list of all errors on the page in one place. This approach is useful for a "busy" form.

To implement the solution, the ControlToValidate attribute must be set to the drop-down list you will be validating. In our case, it is set to ddCountry:

 <asp:CustomValidator  runat="server"  ControlToValidate="ddCountry"  ClientValidationFunction="isItemSelected"  Css  Display="Dynamic"  EnableClientScript="True"  ErrorMessage="Country Must Be Selected"  OnServerValidate="valItemSelected_ServerValidate">   <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:CustomValidator> 

The ClientValidationFunction attribute must be set to the name of the client JavaScript function that will perform the client-side validation, which is done to ensure an item has been selected from the drop down:

 <asp:CustomValidator  runat="server"  ControlToValidate="ddCountry"  ClientValidationFunction="isItemSelected"  Css  Display="Dynamic"  EnableClientScript="True"  ErrorMessage="Country Must Be Selected"  OnServerValidate="valItemSelected_ServerValidate">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:CustomValidator> 

A client script block must be added to the page containing the function named in the ClientValidationFunction attribute of the CustomValidator, as shown in Example 3-7. The function must have source and argument parameters. When the function is called, the source will be set to a reference to the validator that called the function. In this case, it is the "valItemSelected" validator.

The arguments parameter is a structure containing two elements: Value and IsValid. Value contains the current value of the control being validated. In this case, it is the value of the selected item in the drop-down list. In our example, three entries are added to the drop-down list, with the first entry being the Select Country instruction with a value of 0. All legitimate selections from the drop-down contain values greater than 0; therefore, if the value of arguments.Value is less than 1, no selection has been made and the value of arguments.IsValid is set to False to indicate a validation failure. If arguments.Value is greater than 0, then a selection has been made, and arguments.IsValid is set to TRue to indicate the validation passed.

The EnableClientScript attribute is set to true or False according to how you want validation to be performed. Setting the attribute to true causes validation to be performed on the client and on the server when the page 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 are providing client-side JavaScript, so it must be set to true:

 <asp:CustomValidator  runat="server"  ControlToValidate="ddCountry"  ClientValidationFunction="isItemSelected"  Css  Display="Dynamic"  EnableClientScript="True"  ErrorMessage="Country Must Be Selected"  OnServerValidate="valItemSelected_ServerValidate">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:CustomValidator> 

Rather than outputtin gan error message at each control, as was done in all the previous examples in this chapter, we've added a ValidationSummary control to the form in this example to provide in one place a summary of all the errors on the form. When a validation summary is being used, an error message is no longer required between the start and end tags of the validator element. Instead, the ErrorMessage attribute of the validator is set to the error message to display. To provide visual feedback of which control has an error, an arrow image is inserted between the start and end tags of the validator element in our example:

 <asp:CustomValidator  runat="server"  ControlToValidate="ddCountry"  ClientValidationFunction="isItemSelected"  Css  Display="Dynamic"  EnableClientScript="True"  ErrorMessage="Country Must Be Selected"  OnServerValidate="valItemSelected_ServerValidate">   <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:CustomValidator> 

The DisplayMode attribute of the asp:ValidationSummary control defines how the summary is displayed. Valid values are BulletList, List, and SingleParagraph. BulletList will generate a bulleted errors list, which is what we've chosen for our example. List will generate the same list as the BulletList setting but without the bullets. SingleParagraph generates a single HTML paragraph containing all of the error information. The HeaderText attribute is set to the title placed at the top of the errors list.

 <asp:ValidationSummary  Runat="server"  Css  DisplayMode="BulletList"  EnableClientScript="True"  HeaderText="Error Summary" /> 

The sample application's code-behind includes an event handler for the CustomValidator control's ServerValidate event, as shown in Examples 3-8 (VB) and 3-9 (C#). This event handler provides the server-side validation to ensure a country has been selected using the same technique implemented in the client script.

The code-behind includes an event handler for the Save button's click event. This event handler checks to ensure the page is valid (all validation passed) and then performs the processing of the form data.

See Also

Recipes 3.1, 3.2, 3.3, and 3.4

Example 3-7. Form with selection validation (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"      AutoEventWireup="false"  CodeFile="CH03CustomSelectionValidationVB.aspx.vb"  Inherits="ASPNetCookbook.VBExamples.CH03CustomSelectionValidationVB"      title="Custom Selection Validator" %> <asp:Content  Runat="server" ContentPlaceHolder> <script language="javascript" type="text/javascript"> <!--    function isItemSelected(source, arguments)    {  if (arguments.Value < 1)  { arguments.IsValid = false;  }  else  { arguments.IsValid = true;  }    }   //-->   </script>   <div align="center" >    Custom Selection Validation (VB)   </div>   <table align="center" > </tr> <td colspan="2" align="left">   <asp:ValidationSummary  Runat="server" Css DisplayMode="BulletList" EnableClientScript="True" HeaderText="Error Summary" /> </td> </tr> </tr> <td >First Name: </td> <td> <asp:TextBox  Runat="server" Columns="30" Css /> <asp:RequiredFieldValidator  Runat="server" ControlToValidate="txtFirstName" Css Display="Dynamic" EnableClientScript="True" ErrorMessage="First Name Is Required"> <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </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"  ErrorMessage="Last Name Is Required">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:RequiredFieldValidator> </td> </tr> </tr> <td >Age: </td> <td> <asp:TextBox  Runat="server" Columns="30" Css /> <asp:RequiredFieldValidator   Runat="server"  ControlToValidate="txtAge"  Css  Display="Dynamic"  EnableClientScript="True"  ErrorMessage="Age Is Required">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:RequiredFieldValidator>     <asp:RangeValidator  Runat="server"  ControlToValidate="txtAge"  Css  Display="Dynamic"  EnableClientScript="True"  MinimumValue="18"  MaximumValue="99"  Type="Integer"  ErrorMessage="Age Must Be Between 18 and 99">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>     </asp:RangeValidator> </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>  <asp:CustomValidator  runat="server"  ControlToValidate="ddCountry"  ClientValidationFunction="isItemSelected"  Css  Display="Dynamic"  EnableClientScript="True"  ErrorMessage="Country Must Be Selected"  OnServerValidate="valItemSelected_ServerValidate">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>   </asp:CustomValidator> </td> </tr> </tr>    <td >Email Address: </td>    <td> <asp:TextBox  Runat="server" Columns="30" Css />     <asp:requiredfieldvalidator  runat="server" controltovalidate="txtEmailAddress" css display="Dynamic" enableclientscript="True">   <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:requiredfieldvalidator> <asp:RegularExpressionValidator   Runat="server"  ControlToValidate="txtEmailAddress"  Css  Display="Dynamic"  EnableClientScript="True"    ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"        ErrorMessage="Invalid Email Address">   <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>     </asp:RegularExpressionValidator>    </td> </tr> </tr>    <td >Password: </td>    <td>     <asp:TextBox  Runat="server" TextMode="Password" Columns="30" Css /> <asp:RequiredFieldValidator  Runat="server" ControlToValidate="txtPassword1" Css Display="Dynamic" EnableClientScript="True" ErrorMessage="Password Is Required">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:RequiredFieldValidator>     </td> </tr> </tr>    <td >Re-enter Password: </td>    <td> <asp:TextBox  Runat="server" TextMode="Password" Columns="30" Css /> <asp:RequiredFieldValidator  Runat="server" ControlToValidate="txtPassword2" Css Display="Dynamic" EnableClientScript="True" ErrorMessage="Re-Entered Password Is Required">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:RequiredFieldValidator> <asp:CompareValidator  runat="server" ControlToValidate="txtPassword2" ControlToCompare="txtPassword1" Css Display="Dynamic" EnableClientScript="True" ErrorMessage="Both Passwords Must Match">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    </asp:CompareValidator> </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-8. Form with selection validation code-behind (.vb)

 Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples   ''' <summary>   ''' This class provides the code behind for   ''' CH03CustomSelectionValidationVB.aspx   ''' </summary>   Partial Class CH03CustomSelectionValidationVB Inherits System.Web.UI.Page '''***********************************************************************     ''' <summary> ''' This routine provides the event handler for the valItemSelected ''' server validate event. It is responsible for validating that a ''' country has been selected. ''' </summary> ''' ''' <param name="source">Set to the sender of the event</param> ''' <param name="args">Set to the event arguments</param> Protected Sub valItemSelected_ServerValidate(ByVal source As Object, _ ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)    If (ddCountry.SelectedIndex < 1) Then   args.IsValid = False    Else   args.IsValid = True    End If End Sub 'valItemSelected_ServerValidate '''*********************************************************************** ''' <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 'CH03CustomSelectionValidationVB End Namespace 

Example 3-9. Form with selection validation code-behind (.cs)

 using System; namespace ASPNetCookbook.CSExamples {    /// <summary>    /// This class provides the code behind for    /// CH03CustomSelectionValidationCS.aspx    /// </summary>    public partial class CH03CustomSelectionValidationCS   : System.Web.UI.Page    {  ///***********************************************************************  /// <summary>  /// This routine provides the event handler for the valItemSelected server  /// validate event. It is responsible for validating that a country has  /// been selected  /// </summary>  /// <param name="sender">Set to the sender of the event</param>  /// <param name="e">Set to the event arguments</param>  protected void valItemSelected_ServerValidate(Object source,      System.Web.UI.WebControls.ServerValidateEventArgs args)  {    if (ddCountry.SelectedIndex < 1)  {   args.IsValid = false;  }  else  {  args.IsValid = true;  }    } // valItemSelected_ServerValidate    ///***********************************************************************    /// <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   } //CH03CustomSelectionValidationCS } 



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

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