Tuesday, 15 November 2011

Validate a single Validation Group in ASP.NET

Sometimes in ASP.NET you will have a form on a page that is made up of multiple components which are then grouped into panels. You can then group these controls into validation groups, not by the panels they are in but by using the ValidationGroup property which is great however as you cycle through each group of controls you have to call

Page.Validate("AddressDetails");
if (!Page.IsValid) .... do something ...

Page.Validate("ContactDetails");
if (!Page.IsValid) ... do something ....

What I found strange was that if there is a problem with the address details Contact details would always return as Invalid. This is because there is no ValidationGroup.IsValid property. Each time you validate a ValidationGroup if it is not valid the Page's IsValid property is flicked to false. Finding another section that is valid does not flip the switch back (nor should it because any invalid section means that the page is truely invalid.

Hmmmm however I want to know each and every group that is invalid from code. The only way that I found to do this was to iterate through the validators on the page, ask them what ValidationGroup they are in, ask them to validate and then return the result.

This code is for use in the new manual input fields being introduced into our Network Server Audit and Change Tracking system

 /// <summary>
    /// Validates the controls within the specified validation group and returns true if all controls in this group are valid
    /// </summary>
    /// <param name="ValidationGroup">The name of the validation group. This field is not case-sensitive</param>
    /// <returns>A boolean value to determine if all controls within this validation group are valid.</returns>
    private bool IsValid(string ValidationGroup)
    {
        foreach (IValidator Validator in Page.Validators)
        {
            if (Validator is BaseValidator)
            {
                BaseValidator BaseValidator = (BaseValidator)Validator;
                BaseValidator.Validate();
                if (BaseValidator.ValidationGroup.ToLower().Trim() == ValidationGroup.ToLower().Trim() && !BaseValidator.IsValid) return false;
            }
        }
        return true;
    }

No comments:

Post a Comment