Using ValidationSummary Control in MasterPage

The following example demonstrates how to use the ValidationSummary control inside a MasterPage. Since the ValidationSummary control is in masterpage, assuming all the content pages are derived from MasterPage, there is just a single instance of this Summary control throughout the application. So any change in behaviour/look-&-feel of the Validation-Summary can be controlled from one central place, hence gets maintainence easy, for future.

It has the following advantages/features.
1) The ValidationGroup is NOT hardcoded in the ValidationSummary control. The current relevant “ValidationGroup” is passed dynamically as a “function argument”, on the click of whatever submit button.
2) The content page has more than 1 ValidationGroups under separate UpdatePanels & the ValidationSummary correctly fires the relevant validations, conditionally.
3) The button control causing the postback, does NOT have the ValidationGroup property hardcoded.
4) For all the controls, on which the validations fail, the respective bordercolor turns red.
5) Runs okay in IE, Firefox and Safari.

MasterPage markup

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage1.master.cs" Inherits="MasterPage1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript"    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">    </script>
    <script type="text/javascript" src="JS/ValidationScripts.js"    ></script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
        <ajaxToolkit:ToolkitScriptManager runat="Server" ID="ScriptManager1" />
        <div>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>

Content Page markup/codebehind

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage1.master" AutoEventWireup="true" CodeFile="UsingMasterPageValSummaryContentPage1.aspx.cs" Inherits="UsingMasterPageValSummaryContentPage1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
    function pageLoad(sender, args) {
        if (!args.get_isPartialLoad()) {  //Client side if !IsPostback
            TakeValsDisplayOff();
        }
    }
</script>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"><ContentTemplate>
<fieldset>
<ul>
<li>Field1: 
<asp:TextBox id="txtField1" runat="server" MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqVal" runat="server" ControlToValidate="txtField1" ErrorMessage="Please enter Field1" ValidationGroup="Field1" Text="Please enter Field1" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regvField1" runat="server" ControlToValidate="txtField1" ValidationGroup="Field1"    
     ValidationExpression="^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$"
     ForeColor="Red" ErrorMessage="Incorrect Field1 format" Text="Incorrect Field1 format" ></asp:RegularExpressionValidator>
</li>
<li>
<asp:Button ID="btnsubmit" runat="server" OnClientClick="TakeValsDisplayOff();return ValidateNow('Field1');" onclick="btnsubmit_Click"/>
<input type="button" id="reset1" runat="server" value="" class="resetbtn" onclick="ClearAll(); return false;"  />
</li>
</ul>
</fieldset>
</ContentTemplate></asp:UpdatePanel>

<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"><ContentTemplate>           
<fieldset>
<ul>
<li>Address: 
<asp:TextBox ID="txt1" runat="server" MaxLength="150"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqAddr1" runat="server" ErrorMessage="txt1 Required" ValidationGroup="Field2" ControlToValidate="txt1" ForeColor="Red" Text="txt1 Required" ></asp:RequiredFieldValidator>
</li>
<li>Address 2:
<asp:TextBox ID="txt2" runat="server" MaxLength="150"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="txt2 Required" ValidationGroup="Field2" ControlToValidate="txt2" ForeColor="Red" Text="txt2 Required" ></asp:RequiredFieldValidator>
</li>                   
<li >
<asp:Button ID="Button1" runat="server" OnClientClick="TakeValsDisplayOff();return ValidateNow('Field2');" onclick="Button1_Click"/>
<input type="button" id="Submit1" runat="server" value="" class="resetbtn" onclick="ClearAll(); return false;"  />
</li>
</ul>
</fieldset>
</ContentTemplate></asp:UpdatePanel> 
</asp:Content>

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

public partial class UsingMasterPageValSummaryContentPage1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("Field1");
        if (!Page.IsValid)
        {
            return;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Page.Validate("Field2");
        if (!Page.IsValid)
        {
            return;
        }
    }
}

 

Javascript file

function TakeValsDisplayOff() {
    for (var i = 0; i < Page_Validators.length; i++) {
        var val = Page_Validators[i];
        val.style.display = 'none';
        val.isvalid = true;
        var ctrl = document.getElementById(val.controltovalidate);
        if (ctrl != null && ctrl.style != null) {
            ctrl.style.borderColor = '';
        }
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit();
}

function My_PageClient_Validate(CurrValGrp) {
    for (i = 0; i < Page_Validators.length; i++) {
        var val = Page_Validators[i];
        if (val.validationGroup == CurrValGrp) {
            ValidatorValidate(Page_Validators[i], CurrValGrp, null);
        }
    }
}

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) {
                if (!CheckValidatorsForControl(ctrl)) {
                    ctrl.style.borderColor = 'red';
                    val.style.display = 'inline';
                }
                else {
                    ctrl.style.borderColor = '';
                    val.style.display = 'none';
                }
            }
        }
    }
}

function TakeMultipleValsDisplayOff() {
    for (var i = 0; i < Page_Validators.length; i++) {
        var val = Page_Validators[i];
        if ((val.isvalid) && (val.style.display == 'inline')) {
            val.style.display = 'none';
        }
    }
}

function ClearAll() {
    TakeValsDisplayOff();
    $("input[type='text']").val("");
}

function CheckValidatorsForControl(control) {
    for (var i = 0; i < control.Validators.length; i++) {
        if (!control.Validators[i].isvalid) {
            return false;
        }
    }
    return true;
}

function ValidateNow(CurrValGrp) {
    My_PageClient_Validate(CurrValGrp);
    fnOnUpdateValidators(CurrValGrp);
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit();
    TakeMultipleValsDisplayOff();
    if (!Page_IsValid) {
        return false;
    }
    return true;
}

That’s it. Hope this was usefull. Thanks for reading.

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