Changes to the Validation Controls in ASP.NET 2.0

 

Stephen Walther
Microsoft Corporation

July 2004

Applies to:
   Microsoft ASP.NET 2.0
   Visual Studio .NET

Summary: While ASP.NET 1.x supported validating user input, ASP.NET 2.0 increases the flexibility of the validation through the addition of validation groups. This article looks at this new feature, and shows you how you can use it in a number of common scenarios. (12 printed pages)

Contents

Understanding Validation Groups
Using Validation Groups
Adding a Search Form to a Page
Using Validation Groups with the GridView and DetailsView Control
Conclusion

ASP.NET 2.0 includes a new feature which enables you to group form controls into distinct validation groups. This article discusses how you can take advantage of validation groups in complex form validation scenarios.

Two common validation scenarios are discussed in this article. First, you learn how to take advantage of validation groups when adding a search box to a Web page. Next, we'll discuss methods for using validation groups with databinding controls such as the GridView control.

Understanding Validation Groups

The ASP.NET 1.x framework included a rich set of validation controls that made it easy to validate form data before submitting the data to a server. You could use these controls to perform such validation tasks as checking for a required field value, comparing the value of a form field against a regular expression, comparing the value of one form field against another, and performing custom validation. The ASP.NET 2.0 framework includes the very same set of validation controls.

Developers faced one important limitation when using the validation controls. Since an ASP.NET page can include only one server-side form, there was no way to present multiple forms that included validation on the same page. Submitting any form in a page would trigger validation of all of the forms in the page.

This problem is solved in the ASP.NET 2.0 framework with the introduction of validation groups. In the ASP.NET 2.0 framework, the form controls, the button controls, and the validation controls have been modified to support a new property named ValidationGroup. Form controls in separate validation groups are validated independently.

Using Validation Groups

The page in Listing 1 illustrates how you can use validation groups with form controls (see Figure 1). This page contains two TextBox controls. Each TextBox control is associated with a RequiredFieldValidator control. Since the TextBox controls are in different validation groups, however, you can submit the TextBox controls independently.

ms379607.validation_fig01(en-US,VS.80).gif

Figure 1. Using validation groups with form controls

Listing 1. A page with two validation groups

[Visual Basic .NET]

<%@ Page Language="vb" %>
<script runat="server">
    Sub Group1Click(ByVal s As Object, ByVal e As EventArgs)
        If Page.IsValid Then
            lblResult.Text = "Group 1 Submitted"
        End If
    End Sub

    Sub Group2Click(ByVal s As Object, ByVal e As EventArgs)
        If Page.IsValid Then
            lblResult.Text = "Group 2 Submitted"
        End If
    End Sub
</script>
<html>
<head runat="server">
    <title>Validation Groups</title>
</head>
<body>
    <form runat="server">
    <asp:Label ID="lblResult" Runat="Server" />
    
    <fieldset style="padding:20px">
    <legend>Group 1</legend>
        
    <asp:TextBox
        id="TextBox1"
        Runat="Server" />
    <asp:Button
        ValidationGroup="Group1"
        Text="Submit"
        OnClick="Group1Click"
        Runat="Server" />
    <asp:RequiredFieldValidator 
        ValidationGroup="Group1"
        ControlToValidate="TextBox1"
        Text="(required)"
        Runat="Server" />
        
    </fieldset>
        
    <fieldset style="padding:20px">
    <legend>Group 2</legend>
        
    <asp:TextBox
        id="TextBox2"
        Runat="Server" />
    <asp:Button
        ValidationGroup="Group2"
        Text="Submit"
        OnClick="Group2Click"
        Runat="Server" />
    <asp:RequiredFieldValidator 
        ValidationGroup="Group2"
        ControlToValidate="TextBox2"
        Text="(required)"
        Runat="Server" />
        
    </fieldset>
        
    </form>
</body>
</html>

[C#]

<%@ Page Language="C#" %>
<script runat="server">
    void Group1Click(Object s, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblResult.Text = "Group 1 Submitted";
        }
    }
    void Group2Click(Object s, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblResult.Text = "Group 2 Submitted";
        }
    }
</script>
<html>
<head runat="server">
    <title>Validation Groups</title>
</head>
<body>
    <form runat="server">
    <asp:Label ID="lblResult" Runat="Server" />
    
    <fieldset style="padding:20px">
    <legend>Group 1</legend>
        
    <asp:TextBox
        id="TextBox1"
        Runat="Server" />
    <asp:Button
        ValidationGroup="Group1"
        Text="Submit"
        OnClick="Group1Click"
        Runat="Server" />
    <asp:RequiredFieldValidator
        ValidationGroup="Group1"
        ControlToValidate="TextBox1"
        Text="(required)"
        Runat="Server" />
        
    </fieldset>
        
    <fieldset style="padding:20px">
    <legend>Group 2</legend>
        
    <asp:TextBox
        id="TextBox2"
        Runat="Server" />
    <asp:Button 
        ValidationGroup="Group2"
        Text="Submit"
        OnClick="Group2Click"
        Runat="Server" />
    <asp:RequiredFieldValidator 
        ValidationGroup="Group2"
        ControlToValidate="TextBox2"
        Text="(required)"
        Runat="Server" />
        
    </fieldset>
        
    </form>
</body>
</html>

In Listing 1, you should notice that the Page.IsValid property is checked when the page is submitted. This property will return the value true just in case there are no validation errors associated with the form controls in the validation group submitted. Don't forget to check this property. Otherwise, you will run into problems when using validation with downlevel browsers such as Netscape.

You also should be aware that the values of both TextBox controls are submitted to the server, even though the TextBox controls are contained in distinct validation groups. When you click the button associated with the first validation group, the values entered into both TextBox controls are submitted to the server.

Adding a Search Form to a Page

Many Web sites include a simple search box at the top of every page. This feature was surprisingly difficult to implement in the ASP.NET 1.x framework. If the containing page also contained a form, and the form included validation controls, then the validation controls would be triggered whenever you submitted the contents of the search box.

The problem is illustrated in Figure 2. When a search phrase is submitted, the RequiredFieldValidator in the body of the page is triggered, and the contents of the search box are not submitted to the server.

In the ASP.NET 2.0 framework, you can easily handle this problem by using validation groups. The page in Listing 2 illustrates how you can add an independent search box to a page that also contains a validated form.

ms379607.validation_fig02(en-US,VS.80).gif

Figure 2. Search form error

Listing 2. A page with both a search box and survey form

<html>
<head runat="server">
    <title>Search Box</title>
</head>
<body>
    <form runat="server">
    <table bgcolor="blue" width="100%">
    <tr>
        <td align="right">
        <asp:RequiredFieldValidator
            ControlToValidate="txtSearch"
            Text="(required)"
            ValidationGroup="SearchGroup"
            SetFocusOnError="true"
            Runat="Server" />
        <asp:TextBox 
            ID="txtSearch" 
            Runat="Server" />
        <asp:Button 
            Text="Search"
            ValidationGroup="SearchGroup"
            Runat="Server" />
        </td>
    </tr>
    </table>
    <h1>Website User Survey</h1>
    
    What is your annual income?
    <br />
    <asp:TextBox 
        ID="txtIncome" 
        Runat="Server" />
    
    <asp:RequiredFieldValidator
        ControlToValidate="txtIncome"
        Text="(required)"
        Runat="Server" />
    
    <br /><br />
    
    <asp:Button 
        Text="Submit Survey" 
        Runat="Server" />
    
    </form>
</body>
</html>

The search box is created in the HTML table that appears at the top of the page. Notice that both the RequiredFieldValidator control and Button control have a ValidationGroup property. The ValidationGroup property accepts any string. In this case, both controls are assigned the value SearchGroup.

The body of the page contains a TextBox control, a RequiredFieldValidator control, and a Button control, which are used to retrieve the user's annual income. These controls do not have a ValidationGroup property defined. When you click the Search button, the RequiredFieldValidator in the body of the page is not triggered, since it is not part of the same validation group as the Search button.

There is one final aspect of the page in Listing 2 that you should notice. The RequiredFieldValidator control associated with the search box has a SetFocusOnError property declared. This property is new to the ASP.NET 2.0 framework. When this property has the value true, and there is a validation error, whatever control is associated with the validation control automatically receives browser focus.

Using Validation Groups with the GridView and DetailsView Control

Another situation, in which you will want to take advantage of validation groups, concerns the GridView and DetailsView controls. Imagine that you want to display a list of editable records using a GridView control. Furthermore, imagine that you want to enable users to insert new records with a DetailsView control (see Figure 3). In that case, you might encounter a validation conflict.

If a user attempts to edit a record in the GridView, and the DetailsView includes validation controls, then the edit will fail. The problem, once again, results from the fact that you have two logical forms located on the same page. The solution is to place the controls contained in the DetailsView control in a separate validation group.

The page in Listing 3 contains a GridView and a DetailsView control, which can be used to edit existing authors and insert new authors into the Authors database table.

Click here for larger image.

Figure 3. Inserting records with a DetailsView control

Listing 3. Editing Authors with a GridView and DetailsView control

<html>
<head runat="server">
    <title>Edit Grid</title>
</head>
<body>
    <form runat="server">
    <table><tr><td valign="top">
     
    <asp:GridView
        DataSourceID="AuthorSource"
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        DataKeyNames="au_id"
        CellPadding="5"
        Runat="Server" />
    
    </td><td valign="top">
 
    <asp:DetailsView
        DataSourceID="AuthorSource"
        AutoGenerateRows="false"
        DefaultMode="Insert"
        CellPadding="5"
        HeaderText="Add New Author"
        Runat="Server">
        <Fields>
            <asp:TemplateField HeaderText="SS#">
            <EditItemTemplate>
                <asp:TextBox   
                    id="txtSSN" 
                    Text='<%#Bind("au_id")%>'
                    Runat="Server" />
                <asp:RequiredFieldValidator 
                    ValidationGroup="InsertAuthor"
                    ControlToValidate="txtSSN"
                    Text="(required)"
                    Runat="Server" />
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Last Name">
            <EditItemTemplate>
                <asp:TextBox   
                    id="txtLastName" 
                    Text='<%#Bind("au_lname")%>'
                    Runat="Server" />
                <asp:RequiredFieldValidator
                    ValidationGroup="InsertAuthor"
                    ControlToValidate="txtLastName"
                    Text="(required)"
                    Runat="Server" /> 
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="First Name">
            <EditItemTemplate>
                <asp:TextBox   
                    id="txtFirstName" 
                    Text='<%#Bind("au_fname")%>'
                    Runat="Server" />
                <asp:RequiredFieldValidator
                    ValidationGroup="InsertAuthor"
                    ControlToValidate="txtFirstName"
                    Text="(required)"
                    Runat="Server" /> 
            </EditItemTemplate>
            </asp:TemplateField>
   
            <asp:CheckBoxField
                HeaderText="Contract"
                DataField="contract" />
                
            <asp:CommandField 
             CausesValidation="true"
                ValidationGroup="InsertAuthor" 
                ShowInsertButton="true"
                InsertText="Add Author" />
                    
         </Fields>
    </asp:DetailsView>
 
    </td></tr></table>
 
    <asp:SqlDataSource
        id="AuthorSource"
        ConnectionString=
          "Server=localhost;Database=pubs;Trusted_Connection=true"
        SelectCommand=
          "SELECT au_id,au_lname,au_fname,contract FROM Authors"
        DeleteCommand="DELETE Authors WHERE au_id=@au_id"
        UpdateCommand="UPDATE Authors SET 
            au_lname=@au_lname,
            au_fname=@au_fname,contract=@contract
            WHERE au_id=@au_id"
        InsertCommand="INSERT Authors 
            (au_id,au_lname,au_fname,contract) 
            VALUES (@au_id,@au_lname,@au_fname,@contract)"
        Runat="Server" />
  
    </form>
</body>
</html>

Each of the form fields displayed by the DetailsView control in Listing 3 has an associated RequiredFieldValidator control. Each RequiredFieldValidator is part of the InsertAuthor validation group. Since the DetailsView control is part of a different validation group than the GridView control, there is no validation conflict when you edit an author record in the GridView control.

Conclusion

Validation groups elegantly solve an important problem faced by developers in the ASP.NET 1.x framework. By taking advantage of validation groups, you can add more than one logical form to a page. We've seen, in this article, how you can use validation groups in two common scenarios: You learned how to use validation groups when adding a search box to a page, and when combining a GridView with a DetailsView control.

 

About the author

Stephen Walther wrote the best-selling book on ASP.NET, ASP.NET Unleashed. He was also the architect and lead developer of the ASP.NET Community Starter Kit, a sample ASP.NET application produced by Microsoft. He has provided ASP.NET training to companies across the United States, including NASA and Microsoft, through his company Superexpert (https://www.superexpert.com).

© Microsoft Corporation. All rights reserved.