Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 31-Oct-2014 Authors
All Time Authors
Sourav.Kayal
39750
SheoNarayan
38050
Niladri.biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Working with CustomValidator control in ASP.NET

SheoNarayan
Posted by under ASP.NET category on for Beginner level | Views : 131745 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
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!

Page copy protected against web site content infringement by Copyscape
About the Author

SheoNarayan

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Microsoft_MVP,Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com

Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)