Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 13732 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > Working with CustomValidator control in ASP.NET

Working with CustomValidator control in ASP.NET

Article posted by SheoNarayan on 8/19/2009 | Views: 44419 | Category: ASP.NET | Level: Beginner red flag

Advertisements

Advertisements
This article shows how to use CustomValidator validation control that is available in ASP.NET out of the box.

Introduction

CustomValidator control is used to validate a input control with user-defined function either from server side or client side. Generally this control is used when you feel that no other validation controls provided out of the box in asp.net fit in your requirement. The interesting stuff in this control is that you have ability to validate your input data both from Client side using JavaScript and Server side by writing your code in code behind file in any of the .NET supported programming language.

The basic tutorials about this control had been written by me long back that is available here. In this article, we shall try to dig more into this control.

In order to explain this, I have taken a simple example of validating a TextBox for its length of characters through JavaScript at client side and validating the input for a valid email id through code behind in Server side.

Creating a Simple Form

Drag and drop a TextBox, Button and a Custom Validator control from the toolbar or you may prefer copying below code into your page as well to see how this control works.

<h3>Custom Validator</h3>

<asp:TextBox ID="txtEmail" AutoCompleteType="None" runat="server"></asp:TextBox>

<asp:CustomValidator ID="CV1" runat="Server" ClientValidationFunction="JSValidate"

OnServerValidate="ServerValidate" Text="At least 8 character long"

ControlToValidate="txtEmail" ValidateEmptyText="True" ErrorMessage="Validation Failed"></asp:CustomValidator>

 

<br />

<asp:Label ID="lblMessage" ForeColor="brown" runat="Server" EnableViewState="False" />

<br />

<asp:Label ID="lblError" ForeColor="red" runat="Server" EnableViewState="False" />

<p>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitThisForm" />

</p>



Notice the CustomValidator control here and focus on two properties called ClientValidationFunction and OnServerValidate. As their name suggests, the first one is to validate the input value of the TextBox from client side (JSValidate function) and other is to validate the input value from server side (ServerValidate method).

Lets see code for both functions here.

Client Side Function

When the Submit button will be clicked, first ClientValidationFunction function will fire that will try to validate the length of the characters entered into the TextBox, refer to the code below.

<script language="javascript" type="text/javascript">

function JSValidate(source, args)

{

var element = document.getElementById('<%=txtEmail.ClientID %>');

if (element.value.length >= 8) // you can also write args.Value

{

args.IsValid = true;

}

else

{

args.IsValid = false;

}

}

</script>

Note: It is important to maintain the definition of the function both at client side and server side. You can notice that above function has two parameter called source and args. As we are worried about the TextBox value here so first we need to get the id of the TextBox, I have got it using ClientID property of the TextBox control and have stored into the element variable. In the following line I am checking the length of the TextBox to see if its more than 8 characters and setting the value of IsValid property of the args parameter to true / false.

Setting the IsValid property of args tells the Validator function whether the client side validation has failed or passed. If failed, it will show the error Text specified in the CustomValidator control and will not submit the form else the form will be submitted to the server.

Get solutions of .NET problems with video explanations, .pdf and source code in .NET How to's.

Server Side Function

Once the client side validation has passed, Server side validation function ie. ServerValidate will fire. In this method, I am checking the TextBox value against the regular expression and if it is valid then assigning the value of IsValid property of the args parameter to true else false. Notice the signature of the Server Side method, this is same as the JavaScript function we uesd to validate in the client side.

protected void ServerValidate(object source, ServerValidateEventArgs args)

{

RegexStringValidator r = new RegexStringValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

try

{

r.Validate(args.Value);

args.IsValid = true;

}

catch (ArgumentException ee)

{

lblError.Text = "Error occured: Doesn't seem to be valid email id. <br />" +

ee.Message.ToString();

args.IsValid = false;

}

}

 

protected void SubmitThisForm(object sender, EventArgs e)

{

if (Page.IsValid)

{

lblMessage.Text = "Success: The TextBox value is: <b>" + txtEmail.Text + "</b>";

}

}

Irrespective of the result of the Server side validation method, the onclick event of the Submit button will fire. To avoid processing the form in the OnClick event in case of Server side validation failed, we need to check for the validity of the page by using Page.IsValid, this ensures that all validation control placed in the .aspx page has passed successfully. If Page.IsValid returns true then we can go ahead with the processing of the form as shown in the SubmitThisForm method.


Hope this simple and basic article will help beginners to know how to use CustomValidator controls in ASP.NET web forms. please subscribe for the subsequent article alert directly in your email box. Thanks and Happy coding!

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

>> Write Response - Respond to this post and get points
Related Posts

We are In many sites to save HINDI data in SQL data base. But is too difficult to insert HINDI font in data base. I am tried to solve this problem. Then he work exactly .

In this article we shall learn how to fire Server Side method on click of the button, how to access the CommandName property of the asp: Button (using OnCommand event) and what is the use of it and how to access the CommandName property of the asp:Button (using OnClick event) and what is the use of it.

One of the most important components in a project is the DAL component. Many developers end up creating their own DAL component which is pretty time consuming. A Microsoft enterprise application block has a very decent and time tested DAL component i.e. the Enterprise data application blocks. This tutorial will run through the necessary steps of how you can use Enterprise data application blocks in your DAL component.

Limiting the File Upload size using ASP.NET

In this article we will discuss an upcoming code review tool StyleCop. We will understand the basics and do a small sample of code review practically to understand how StyleCop works. I have been writing and recording videos on architecture, design patterns, UML, enterprise blocks, estimation, and code reviews. You can view all my videos on http://www.questpond.com . Any feedbacks do email me at shiv_koirala at yahoo.com You can read my previous article on code reviews using FXCOP http://www.dotnetfunda.com/articles/article175.aspx

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/20/2013 2:16:26 AM