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;
    }

Comments

Popular posts from this blog

Windows Server 2016, 2019, 2022, Windows 10 and Windows 11: Date and time "Some settings are managed by your organization".

TFTPD32 or TFTPD64 reports Bind error 10013 An attempt was made to access a socket in a way forbidden by its access permissions.

Enable function lock for F1-F12 on HP ZBook mobile workstations