Rob Bell

Server-Side ValidationGroup Switching

Often when validating a page in ASP.NET there’s the need to switch between ValidationGroups. A good example is a shopping cart where the user can choose to have products delivered to the account address or enter an alternative address, all within one page submission. If the user chooses to use an alternative address we need to validate that the required fields for the new address have been completed; if they decide to use their existing address then we need to validate that instead. Below is typical markup for this scenario:

<asp:Label AssociatedControlID="AddressLine1" runat="server">
    Address Line 1
</asp:Label>
<asp:Textbox ID="AddressLine1" runat="server" />
<asp:RequiredFieldValidator runat="server" Text="Required"
 ControlToValidate="AddressLine1" ValidationGroup="PrimaryAddress" />
...

<asp:RadioButtonList ID="AddressSelect" runat="server">
    <asp:ListItem Value="primary" Selected="True">
        Use the address above
    </asp:ListItem>
    <asp:ListItem Value="alternative">
        Use a different address
    </asp:ListItem>
</asp:RadioButtonList>

<asp:Label AssociatedControlID="AltAddressLine1" runat="server">
    Address Line 1
</asp:Label>
<asp:Textbox ID="AltAddressLine1" runat="server" />
<asp:RequiredFieldValidator runat="server" Text="Required"
ControlToValidate="AltAddressLine1" ValidationGroup="AltAddress" />
...

<asp:Button ID="Submit" runat="server" Text="Submit" 
OnClick="Submit_Click" />

To enable switching between ValidationGroups leave the ValidationGroup property of the submit button empty and instead select which ValidationGroup to validate on the button Click event by calling Page.Validate(groupName). You can then check the Page.IsValid value to see if the call was successful.

protected void Submit_Click(object sender, EventArgs e)
{
    if(AddressSelect.SelectedValue == "primary")
    {
        Page.Validate("PrimaryAddress");
    }
    else
    {
        Page.Validate("AltAddress");
    }

    if(Page.IsValid)
    {
        // Continue
    }
}

To validate multiple different groups we can make multiple calls to Page.Validate(), passing in the different group names. The Page.IsValid value will be false if any of the calls to Page.Validate() fail. The example below will always validate the primary address, but only validate the alternative address when the “Use a different address” option is selected:

Page.Validate("PrimaryAddress");

if(AddressSelect.SelectedValue == "alternative")
{
    Page.Validate("AltAddress");
}

if(Page.IsValid)
{
    // Continue
}

This article only covers server-side switching and the examples above will only work if all validation controls have EnableClientScript set to false.

Published

19 May 2009

Category

Articles

Tagged

.NET, C#

No comments