Toggle Validators using ValidationGroup and set BackgroundColor of the Validation-failed control.

The Scenario: Sometimes we may come across certain design , where a particular set of validators need to be active/Inactive, depending on certain criteria.
In this post, I’m using the relevant active-set-of-validator’s —- “ValidationGroup” property —–  to make sure the page is valid at client side as well as on server.
The Solution: The best part of using “ValidationGroup” to control which validators stay active as per design — is that , we don’t have to manually disable other irrelevant validators. ASP.Net automatically takes, only those validators which belong to the current active Validation Group.
On the client-end, Page_ClientValidate function takes “ValidationGroup” as an argument.We need to run the Page_ClientValidate function, which updates the page_IsValid value to the most latest/updated/correct status. Also on client side, I change the background-color of the controls to red, for whom validation failed.
If validation succeeds at client end , on server side I run a for loop for a given ValidationGroup.  Here’s the complete working copy

<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<script language="javascript" type="text/javascript">
function abc() {
$get('<%= Label1.ClientID %>').innerHTML = "";
var ddlVal = $get('<%= ddl1.ClientID %>').value;
if (ddlVal == "cc") {
    var v2 = Page_ClientValidate("ValSumm9");
    fnOnUpdateValidators("ValSumm9");
    return v2;
}
if (ddlVal == "bb") {
    var v1 = Page_ClientValidate("ValSumm1");
    fnOnUpdateValidators("ValSumm1");
    return v1;
}
}

function fnOnUpdateValidators(CurrValGrp) {
for (var i = 0; i < Page_Validators.length; i++) {
    var val = Page_Validators[i];
    var ctrl = document.getElementById(val.controltovalidate);
            
    if (ctrl != null && ctrl.style != null) {
        if ((val.validationGroup == CurrValGrp) && (!CheckValidatorsForControl(ctrl))) {
            ctrl.style.backgroundColor = 'red';
        }
        else {
            ctrl.style.backgroundColor = '';
        }
        ValidatorUpdateIsValid();
        ValidationSummaryOnSubmit(val.validationGroup);
    }
}
}

function CheckValidatorsForControl(control) {
for (var i = 0; i < control.Validators.length; i++) {
    if (!control.Validators[i].isvalid) {
        return false;
    }
}
return true;
}
</script>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset>
<asp:ValidationSummary ID="Summary1" runat="server" ValidationGroup="ValSumm1"/>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="ValSumm9"/>
<asp:Label ID="Label1" runat="server" Text="Grp1"></asp:Label>
<br />
<asp:DropDownList ID="ddl1" runat="server" AppendDataBoundItems="true">
            <asp:ListItem Text="Select Validation Group" Value=""></asp:ListItem>
            <asp:ListItem Text="ValSumm1" Value="bb"></asp:ListItem>
            <asp:ListItem Text="ValSumm9" Value="cc"></asp:ListItem>
        </asp:DropDownList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddl1"  
        ErrorMessage="ValGroup is required." Text="ValGroup is required" ></asp:RequiredFieldValidator>
        <br />
<fieldset>
ValidationGroup=ValSumm1
<br /><br />
<asp:TextBox ID="txt1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="Req1" runat="server" ControlToValidate="txt1"  ErrorMessage="Text1 is required." 
Text="Text1 is required" ValidationGroup="ValSumm1"></asp:RequiredFieldValidator>
&nbsp;
<asp:DropDownList ID="ddl2" runat="server" AppendDataBoundItems="true" >
    <asp:ListItem Value="">Select Item</asp:ListItem>
    <asp:ListItem Value="1" Text="1"></asp:ListItem>
    <asp:ListItem Value="2" Text="2"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="Req4" runat="server" ControlToValidate="ddl2"  ErrorMessage="Item is required." 
Text="Item is required" ValidationGroup="ValSumm1"></asp:RequiredFieldValidator>
</fieldset>

<br /><br />

<fieldset>
ValidationGroup=ValSumm9
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="ValSumm9" ></asp:TextBox>
<asp:RequiredFieldValidator ID="Req2" runat="server" ControlToValidate="TextBox1" ErrorMessage="Text2 is required." 
Text="Text2 is required." ValidationGroup="ValSumm9"></asp:RequiredFieldValidator>
&nbsp;
<asp:TextBox ID="TextBox2" runat="server" ValidationGroup="ValSumm9"></asp:TextBox>
<asp:RequiredFieldValidator ID="Req3" runat="server" ErrorMessage="Text3 is required." ForeColor="Red" 
ControlToValidate="TextBox2"  Text="Text3 is required." ValidationGroup="ValSumm9"></asp:RequiredFieldValidator>  
<br />
</fieldset>

<asp:Button ID="btn1" runat="server" Text="Submit1"  OnClientClick="return abc();" onclick="btn1_Click"/>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
     
&nbsp;&nbsp;
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset></fieldset>
<asp:Label ID="Label2" runat="server" Text="Grp2"></asp:Label>
<asp:ValidationSummary ID="Summary2" runat="server" ValidationGroup="ValSumm2"/>
<asp:TextBox ID="txt2" runat="server" CausesValidation="false"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt2" 
ErrorMessage="Text2 is required." Text="*" ValidationGroup="ValSumm2"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btn2" runat="server" Text="Submit2" ValidationGroup="ValSumm2" OnClientClick="" onclick="btn2_Click" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "";
        Label2.Text = "";
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        Label1.Text = "";
        string x = "";
        if (ddl1.SelectedValue == "cc") //Rest all comes under ValidationGroup=ValSumm9
        {
            if (!CheckGroupValidations("ValSumm9"))
            {
                return;
            }
            x = "UpdatePanel1 validated. New Text = " + TextBox1.Text + "<br>";
        }
        if (ddl1.SelectedValue == "bb")  //This selection covers the ValidationGroup=ValSumm1
        {
            if (!CheckGroupValidations("ValSumm1"))
            {
                return;
            }
            x = "UpdatePanel1 validated. New Text = " + txt1.Text + "<br>";
        }
    }
    private bool CheckGroupValidations(string strValGrp)
    {
        foreach (BaseValidator val in Page.Validators)
        {
            if (val.ValidationGroup == strValGrp)
            {
                val.Validate();
                if (!val.IsValid)
                {
                    return false;
                }
            }
        }
        return true;
    }
    protected void btn2_Click(object sender, EventArgs e)
    {
        Label2.Text = "";
        Page.Validate("ValSumm2");
        if (!Page.IsValid)
        {
            return;
        }
        Label2.Text = "UpdatePanel2 validated. New Text = " + txt2.Text + "<br>";
    }

Advertisements
This entry was posted in General ASP.Net C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s