Friday, March 30, 2012

Asp.Net - ValidationSummary using ValidationGroup

In Asp.Net the ValidationSummary control consolidates the validation detials and error messages of all the validation controls in the page and provides a summary report of all the validation failures in the page.

Suppose we have a large page and we need to group the validations in the page based on specific groups, here we need to use the ValidationGroup property, the ValidationGroup property should be set to the controls which are part of the group, the ValidationSummary control and the button which will handle the submit/postback of this group.

Here’s the code below


<
asp:TextBox id="txtPhone" runat="server" CssClass="text" MaxLength="12">asp:TextBox>
<asp:RegularExpressionValidator ID="valtxtPhone" runat="server" ControlToValidate="txtPhone" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" Display="None" Text="*" ValidationGroup="valGroup" ErrorMessage="Enter Phone# in the format 999-999-9999" SetFocusOnError="true">asp:RegularExpressionValidator>
<asp:Button ID="cmdSave" runat="server" Text="Save" ValidationGroup="valGroup" />
<asp:ValidationSummary ID="valSummary" runat="server" DisplayMode="List" ValidationGroup="valGroup" ShowMessageBox="True" ShowSummary="False" EnableClientScript="true"/>
Now build and run the project, enter an invalid Phone# in the textbox and click on the Save button. You should get an error message.

Also notice that other validations in the page, which are not bound to this ValidationGroup will not get fired.
That's it, we have implemented the ValidationGroup in the ValidationSummary control for the Asp.Net Validation controls.

Search Flipkart Products:
Flipkart.com