Using the ValidationSummary control with ASP.NET MasterPages

Posted by: Malcolm Sheridan , on 7/16/2009, in Category ASP.NET
Views: 50260
Abstract: The following article demonstrates how to create one validation summary control on a master page and have that display all your validation errors.
Using the ValidationSummary control with ASP.NET MasterPages
 
When you’re building web applications, it is important to validate the data before sending it to the database. If validation fails, a typical thing to do is display any validation errors to the user. This is normally done using the ValidationSummary control. This article will demonstrate how to use a central ValidationSummary control that resides on a master page to display all validation errors.
The key to getting this to work is to be able to set the ValidationGroup for the ValidationSummary from your web content pages. The ValidationGroup gets or sets the group of controls for which the ValidationSummary control displays validation messages. This needs to be changed because most ASP.NET validators have different validation groups.
To begin with open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. Add a master page to the project and name it Site.Master.   Add a ValidationSummary control to the page:
<asp:ValidationSummary ID="valErrorSummary" runat="server" Font-Size="Large" />
To expose this property to your web content pages, you’ll need to create a public property which sets the ValidationGroup property. This will be accessible from the web content pages via the MasterType directive. Add the following code to the master page’s code behind file: 
C#
 
public string ValidationGroup
{
set { valErrorSummary.ValidationGroup = value; }
}
 
VB.NET
 
Public WriteOnly Property ValidationGroup() As String
Set(ByVal value As String)
      valErrorSummary.ValidationGroup = value
End Set
End Property
 
That is basically all you need to do to the master page. The next step is to add a web content page to your project. Accept the default name provided by studio. To be able to call the ValidationGroup property from the web content page, you’ll need to add a new MasterType directive to the web content page:
<%@ MasterType VirtualPath="~/Site.Master" %>
This provides a way to create a strongly typed reference to the master page when the master page is accessed from the Master()()() property. Open the web content page and add the following code to the HTML mark-up:
Surname <asp:TextBox ID="txtSurname" runat="server" ValidationGroup="Surname"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
        ErrorMessage="Surname is required" ControlToValidate="txtSurname"
        Display="None" ValidationGroup="Surname"></asp:RequiredFieldValidator>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Save Data"
        ValidationGroup="Surname" />
 
In the code above there is one TextBox, RequiredFieldValidator and a Button. The RequiredFieldValidator has its Display set to None. This is because if validation fails, we don’t want to display the error message beside the RequiredFieldvalidator, we want it displayed in the master pages ValidationSummary. All three controls have their ValidationGroup property set to Surname. If you ran this code now and entered nothing in the TextBox, you would see nothing telling you to input a surname. Why? Well that is because the you need to set the ValidationSummary’s ValidationGroup to Surname. You have access to the property through the MasterType directive, so add the following code to the page load event: 
C# 
protected void Page_Load(object sender, EventArgs e)
{
Master.ValidationGroup = "Surname";
}
 
VB.NET 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Master.ValidationGroup = "Surname"
End Sub
 
If you ran the project now and fail to enter a surname, you’ll see the error message displayed in the ValidationSummary. 
Error_Message
 

By creating your validation controls this way, you’re eliminating the need to have ValidationSummary controls on each page. This makes administering your project much easier if you need to change any of them.  Master pages are a great way to store central resources.

The entire source code of this article can be downloaded over here 

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by cristian on Monday, August 24, 2009 11:22 AM
Hi I have a problem that i can´t find the solution.

i have 1 txtbox, 1 dropdownlist and 1 select box. The dropdownlist load the select box. below some code to show how i'm validatiing the form

*************************
Script: (validate declaration)
*************************
rules:
{
    cname:
    {
        required:true
        },
        ddlCities:
        {
        required: function (element){            
            return $("#ddlCities").val() < 1;
            }
        }
    },
            
    messages:
    {
        cname:
        {
            required: "<img src='img/cancel.png' with='20' height='20' title='Ingrese el nombre de su empresa'>"                
        },
        ddlCities:
        {
            required: "<img src='img/cancel.png' with='20' height='20' title='Elija un Rubro'>"
        }
    }
******
HTML:

******
<form name="submitform" id="submitform" method="post" action="test.aspx" runat="server">

<input id="cname" name="cname">

<asp:DropDownList ID="ddlStates" runat="server">
            <asp:ListItem Value="none">Select</asp:ListItem>
            <asp:ListItem Value="1">Santa Fè</asp:ListItem>
            <asp:ListItem Value="2">Buenos Aires</asp:ListItem>
        </asp:DropDownList>

        <select ID="ddlCities" runat="server">
            </select>

this code is ok. when the select (ddlCities) don't have an option selected the validate library show the message asking choose one value of the list.

The problem is when i use this code inside of MasterPage, more exactly inside of ContentPlaceHolder. Cry

The text box validtion is ok, but the combo don't work.

I modified the code Script like:-->

*************************
Script: (validate declaration)
*************************
rules:
{
    cname:
    {
        required:true
        },
        <%=ddlCities.ClientID%>:
        {
        required: function (element){            
            return $("#ddlCities").val() < 1;
            }
        }
    },
            
    messages:
    {
        cname:
        {
            required: "<img src='img/cancel.png' with='20' height='20' title='Ingrese el nombre de su empresa'>"                
        },
        <%=ddlCities.ClientID%>:
        {
            required: "<img src='img/cancel.png' with='20' height='20' title='Elija un Rubro'>"
        }
    }

theorically, it should work, but it is not true.....

can you help me with this issue?


thanks in advance

Cristian.-
Comment posted by kannan on Saturday, October 3, 2009 12:33 AM
USING VALIDATION SUMMARY BY SIMPLE WAY...
http://www.onlineatoz.net/onlineatoznet/forum/post/ToolBox-Validation-Control-ValidationSummary.aspx
Comment posted by ajex on Saturday, October 3, 2009 12:35 AM
s its good for validation control thank u kannan
<a href="http://www.onlineatoz.net/onlineatoznet/forum/post/ToolBox-Validation-Control-ValidationSummary.aspx">Validation Summary</a>
Comment posted by Malcolm Sheridan on Saturday, November 28, 2009 5:58 AM
@kannan
Thanks for the link. Your article is different from mine as I was you how to have one ValidationSummary control to cater for all your pages.  Nice article anyway.
Comment posted by Diego on Friday, March 4, 2011 6:39 AM
Thanks for this article so good,
It was a great help to me.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel