Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Set ValidatonGroup for ValidationSummary Control Client-Side...

Here's a handy tip on setting the validation group property for a ASP.NET ValidationSummary Control in JavaScript.

Scenario

We have a large form with three input areas (not my design!). Each input area has its own Save/Cancel button set and its own ValidationGroup. As well, we have a single ValidationSummary control on the master page to display errors raised by the validation controls.

Based upon which Save button user presses, we want to be able to dynamically set the validationGroup on the Validation Summary control so that it picks up the error messages from the validators in the selected validation group – all client-side. 

If you look at the client-side representation of the ValidationSummary control (Page_ValidationSummaries[0]) in a quick watch, you are discouraged when you do not see a property for ValidationGroup, leading you to believe that this value is not exposed as a client-side attribute of the ValidationSummary control:

image

image

However, fear not, when you get into an immediate window, you can ‘manually’ append ".validationGroup" to the ValidationSummary object….. and, it works!

image

And, sure enough in your JavaScript function, you too can set your validation group on your ValidationSummary control:

//-- Dynamically set validation group on a validation summary control.
function SetValidationGroup(validationGroupName) {
    //debugger;
    //-- Check for null validation group name
    if (validationGroupName == null) {
        return;
    }

    //-- Assign validation group name to validationSummary control
    Page_ValidationSummaries[0].validationGroup = validationGroupName;
}

Then, in you button control, add the 'onClientClick="SetValidationGroup(validationGroupName);"

<asp:Button ID="myButton" runat="server" Text=" Save " OnClick="myButtonServerSideEventHandler" ValidationGroup="ValidationGroupForFirstButton"  OnClientClick="SetValidationGroup(ValidationGroupForFirstButton);" />

Keep in mind that this example 'assumes' that you have a single ValidationSummary control (Element 1 of the zero-based Page_ValidationSummaries collection). You know what they say about, "assume."  Add some code to ensure that you are setting the correct ValidationSummary control. 

Hope this helps.

No Comments