Can a button validate more validation groups?

asp.net, validation

Solution

I am adding another answer since adding to my last existing answer would make the answer too big for anyone to read.

In this answer, I have expanded on my last answer so multiple validation groups are `automatically` hooked up both on client-side as well as server-side. This means you do not need to call `Page_ClientValidate("group1,group2")` in JavaScript onclick event of button, since it will occur automatically. Also, the server-side validation for multiple groups will happen automatically.

The markup and code-behind for this is given below. You can try the aspx code that I have provided and test it in a website project. To test if automatic server-side validation occurs, you must set `EnableClientScript="false"` for each of the three validators.

Explanation of approach for automatic validation of multiple groups

If you want to implement multiple validation groups, the following steps need to done in your aspx page. Make sure that in your markup you mention a comma-delimited list of validation groups for `ValidationGroup` property of button control if you need to validate multiple groups at a time.

- you need to override the JavaScriptmethod `IsValidationGroupMatch` by adding JavaScript to end of your aspx page (The code for this override is given at end of markup code below and you can copy/paste it into your aspx page); this is a standard method provided by ASP.Net validation framework.

- you need to hookup the button with multiple validation groups for client-side validation since this is NOT done automatically by ASP.Net; for this, you have to call the method `HookupValidationForMultipleValidationGroups` in code-behind in Page_Load event for each button that has multiple validation groups.(you can copy/paste this method given in second-code snippet into the code-behind of your aspx page)

- you need to override the server-side method `Validate` to add functionality for multiple validation groups since this is missing in ASP.Net.(you can copy/paste this method given in second-code snippet into the code-behind of your aspx page)

Markup of aspx with multiple validation groups for a button

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipleValidationGroupsByOneButton.aspx.cs" Inherits="MultipleValidationGroupsByOneButton" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            TextBox1 : 
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 needs input"  ControlToValidate="TextBox1" ForeColor="Red" ValidationGroup="group1"></asp:RequiredFieldValidator>

            <br />
            <br />
            TextBox2 : 
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="TextBox2 needs input"  ControlToValidate="TextBox2" ForeColor="Red" ValidationGroup="group2"></asp:RequiredFieldValidator>
            <br />
            <br />
            TextBox3 :
             <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="TextBox3 needs input"  ControlToValidate="TextBox3" ForeColor="Red" ValidationGroup="group3"></asp:RequiredFieldValidator>

            <br />
            <br />
        </div>
        <asp:Button ID="btnMultipleValidationGroups" runat="server" Text="Validate group1 and group2" ValidationGroup="group1,group2" OnClick="btnMultipleValidationGroups_Click" />
        <asp:Button ID="btnGroup1" runat="server" Text="Validate only group1" ValidationGroup="group1" OnClick="btnGroup1_Click" />
        <asp:Button ID="btnGroup2" runat="server" Text="Validate only group2" ValidationGroup="group2" OnClick="btnGroup2_Click" />
        <asp:Label ID="lblMessage" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
        <script type="text/javascript">
            window["IsValidationGroupMatch"] = function (control, validationGroup) {
                if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
                    return true;
                }
                var controlGroup = "";
                var isGroupContained = false;
                if (typeof (control.validationGroup) == "string") {
                    controlGroup = control.validationGroup;
                    var controlGroupArray = [];
                    if (validationGroup.indexOf(",") > -1) {
                        controlGroupArray = validationGroup.split(",");// validationGroup.split(",");
                    }
                    for (var i = 0; i < controlGroupArray.length; i++) {
                        if (controlGroupArray[i].trim() == controlGroup.trim()) {
                            isGroupContained = true;
                        }
                    }
                }
                return (controlGroup == validationGroup || isGroupContained);
            }
        </script>
    </form>
</body>
</html>

Code-behind of above aspx page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MultipleValidationGroupsByOneButton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //always call this method in Page Load event for each button with multiple validation groups
        HookupValidationForMultipleValidationGroups(btnMultipleValidationGroups);
    }
    //the method below will automatically hook up a button with multiple validation groups for client-side validation
    private void HookupValidationForMultipleValidationGroups(IButtonControl button)
    {
     if (!Page.IsPostBack && button.ValidationGroup.Contains(","))
     {
        //hook up validation on client-side by emitting the appropriate javascript for onclick  event of the button with multiple validation groups
        PostBackOptions myPostBackOptions = new PostBackOptions((WebControl)button);
        myPostBackOptions.ActionUrl = string.Empty;
        myPostBackOptions.AutoPostBack = false;
        myPostBackOptions.RequiresJavaScriptProtocol = true;
        myPostBackOptions.PerformValidation = true;//THIS true value hooks up the client-side validation
        myPostBackOptions.ClientSubmit = true;
        myPostBackOptions.ValidationGroup = button.ValidationGroup;

        // Add postback script so cleint-side validation is automatically hooked up for control with multiple validation groups
        ((WebControl)button).Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(myPostBackOptions));
     }
    }
    //Override default Validate method so server-side validation of buttons with multiple validation groups occurs automatically 
    public override void Validate(string validationGroup)
    {
        if (validationGroup.Contains(","))
        {
            string[] validationGroups = validationGroup.Split(",".ToCharArray());
            foreach (string group in validationGroups)
            {
                Page.Validate(group);
            }
        }
        base.Validate(validationGroup);
    }
    protected void btnMultipleValidationGroups_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblMessage.Text = "Button with multiple validation groups was clicked";
        }
    }
    protected void btnGroup1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblMessage.Text = "Button with Group1 validation group was clicked";
        }
    }
    protected void btnGroup2_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblMessage.Text = "Button with Group2 validation group was clicked";
        }
    }

}

Problem

I have 3 types of validators: It is part of "VG1" validation group It is part of "VG2" validation group It is not part of any validation groups I have two buttons, B1 and B2. I would like to validate B1.Click if and only if all validators of the first and third type successfully validated the controls associated to them. I would like to validate B2.Click if and only if all validators of the second and third type successfully validated the controls associated to them. Is this possible in ASP.NET? If so, can you tell me how can I do this or where could I read something which would enlighten me in this question? EDIT: ``` function isValidButton1() { var VG1 = Page_ClientValidate("VG1"); var empty = Page_ClientValidate(""); return VG1 && empty; } ``` This works well, however, if VG1 is invalid, then the messages will disappear, because of the validation of the empty group. Is there a solution to show all validation error messages? Thank you. EDIT2: ``` function isValidSaveAsClosed() { Page_ClientValidate(""); Page_ClientValidate("VG1"); var groups = []; groups[0] = undefined; groups[1] = "VG1"; var valid = true; for (var f in Page_Validators) { if (jQuery.inArray(Page_Validators[f].validationGroup, groups) >= 0) { ValidatorValidate(Page_Validators[f]); valid = valid && Page_Validators[f].isvalid; } } return valid; } ``` The function above solves my problem.

Original source