Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET
Article

Understanding ASP.NET Validation Techniques

Rate me:
Please Sign up or sign in to vote.
4.78/5 (26 votes)
22 Feb 2012CPOL8 min read 188.7K   2.9K   42   12
This article aims at understanding the basic validation techniques and controls provided by ASP.NET framework.

Introduction

This article aims at understanding the basic validation techniques and controls provided by ASP.NET framework. We will try to understand which validation control should be used in any particular scenario and then make a small dummy application to illustrate the use of validation controls.

Background

Whenever we have an application that expects user input, then it becomes important to ensure the validity of the data input by the user. We might have scenarios when some data is mandatory for the user to enter. There are scenarios when the user data has to be in some particular format example email ID. There could be scenarios when we want the data to be in some range example date input.

So for all the above mentioned scenarios, if we take the user input without validation, then chances are that we will end up having wrong data with us (perhaps in database). If it is a bad day for us then possibly our application might also end up behaving in an unexpected manner and even crash on us (like if we try to convert a non numeric string to int). Worst case scenario, the user will use the input field to perform SQL injection and cause serious damage to our database. So it is always a good idea to have validation in place whenever we are taking input from the user.

Types of Validation

There are two ways we can perform validation:

  • Client side validation
  • Server side validation

Client Side Validation

Client side validation is something that will happen on users' browser. The validation will occur before the data gets posted back to server. It is a good idea to have client side validation as the user gets to know what needs to be changed immediately, i.e., no trips to servers are made. So from the users' point of view, it gives him fast response and from the developers' point of view, it saves valuable resources of server.

JavaScript is most widely used to perform client side validation. From decades, developers have been using JavaScript for client side validation. It is always a good idea to have knowledge of JavaScript as it gives us full control over client side validation. Now Microsoft is also embracing jQuery in its current versions so perhaps JavaScript and/or Jquery should be the right thing to use for client side validation.

JavaScript provides full control to the developer on how client side validation should happen but developers will have to write the validation code themselves. ASP.NET also provides some validation controls to perform client side validation which could help the developers in putting client side validation in place without writing a lot of code. These controls will also use JavaSscript underneath to perform validations. We will see these controls in a moment.

Server Side Validation

Server side validation occurs at server. The benefit of having server side validation is that if the user somehow bypasses the client side validation (accidentally or deliberately), then we can catch the problem on the server side. So having server side validation provides more security and ensures that no invalid data gets processed by the application.

Server side validation is done by writing our custom logic for validating all the input. ASP.NET also provides us some controls which will facilitate the server side validation and provides a framework for the developers to do the same.

NOTE: Web developer may choose to go with any one type of validation but usually it is a good idea to have client side validation and same validation on server side too. It sure takes some resources of server to validate the already validated data (on client side) but it ensures security and that is always good.

Validation Controls in ASP.NET

The validation controls provided bt ASP.NET are:

  • RequiredFiledValidator
  • CompareValidator
  • RangeValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary

We can tweak these validation control's properties for how to perform validation but first let us look at some properties common to all these controls.

  • ControlToValidate: ID of the control which should be validated by this control.
  • ErrorMessage: This message will be displayed to the user when validation fails. This should always be something which user can read and act upon.
  • Text: This string will be visible where the validation control is placed when validation fails. Usually it is a good idea to set it to "*".

There are few more properties but for now we can move ahead with these properties in mind and see all the validation controls in action.

Validation Summary

It is a good idea to look at this control first. ValidationSummary control is a control which displays the error messages for all the validation controls on the page in one place. If we want to have this control display the error messages for some particular validation controls (possibly because we have multiple ValidationSummary on page), then we can use ValidationGroup property of the controls. Let's move ahead and see how validation summary will be useful for us.

RequiredFieldValidator

This validation control will be used when we are mandating the user input for any particular field. Let's say we have a simple form with name field and we don't want this to be empty. so what we can do is add a RequiredFieldValidator to the page, set the ControlToValidate to the ID of the name input field, set the error message property.

validation image

When we try to do a postback without entering name, then the postback will not happen and the "*" will be displayed in place to our validation control. The ValidationSummary we already added will display the full error message.

validation image

If we look at the timestamp we added on the page, we can verify that the validation is happening on the client side and no postback is happening to the server. If we need to change this to do this validation in server side, then we will have to set the EnableClientScript property of the validation control to false.

CompareValidator

This control will compare the value of its ControlToValidate with ControlToCompare. It uses the comparison operators to do the same. Now let us say we have a hypothetical scenario where we want the same name to be entered twice (not so hypothetical if it would be password) then we can have a CompareValidator in place with the following properties:

validation image

In case we want this control to use some predefined value instead of value in some control, then we can use ValueToCompare property.

Now let's run the page:

validation image

If we look at the timestamp we added on the page, we can verify that the validation is happening on client side and no postback is happening to the server. If we need to change this to do this validation in server side, then we will have to set the EnableClientScript property of the validation control to false.

RangeValidator

In scenarios where we want to ensure that the value entered by the user is in some predefined range, we can use this control. Let us try to add this control on our page and use this to validate the age of the user. We are saying the valid age is between 18 to 50.

validation image

When we run the page:

validation image

If we look at the timestamp we added on the page, we can verify that the validation is happening on the client side and no postback is happening to the server. If we need to change this to do this validation in server side, then we will have to set the EnableClientScript property of the validation control to false.

Regular Expression Validator

RegularExpressionValidator comes in handy when we want input data to be in some specific format. Let us try to do that on our page by asking the user for his email ID. We will be using the RegularExpressionValidator for validating the format of email id.

validation image

Let us run the page.

validation image

CustomValidator

If with all these validation controls provided by ASP.NET, we still find ourselves a scenario where we need customized validation behavior, we can use the CustomValidator Control. Let us try to use this control and perform custom client side as well as server side validation. What we will do is we will check for '-' character in user input and reject the input if '-' is present in any field (assuming a SQL injection attempt). So let us see how can we use CustomValidator for it.

validation image

Now let us look at the client side JavaScript we had to write to provide our custom validation behavior:

JavaScript
function ValidateOnClient(source, arguments)
{
    if( arguments.Value.search('-') != -1)
    {
        arguments.IsValid = false;
    }
}

and when we run the page:

validation image

Now let us do the same by having the validation done at server side. We will do that for the email id field.

validation image
C#
protected void CustomValidator2_ServerValidate
    (object source, ServerValidateEventArgs args)
{
    string value = args.Value;

    if (value.Contains("-"))
    {
        args.IsValid = false;
    }
}

When we enter invalid data in email id field, the validation error will be displayed after postback.

validation image

Summary

Although we can do all the client side and server side validations ourselves using JavaScript and server side code, we could find the validation controls provided by ASP.NET useful in many scenarios. These validation controls give us the flexibility of validating on client side or server side. We can use the ValidationGroup, Page.IsValid properties and Page.validate method to have fine grained control on the validation process.

History

  • 22 Feb 2012: Understanding ASP.NET validation techniques

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
Questionquick revision Pin
Er.Vaibhav Singh Chauhan30-Oct-15 2:25
professionalEr.Vaibhav Singh Chauhan30-Oct-15 2:25 
Questionbest to understand basics of asp.net validations Pin
Er.Vaibhav Singh Chauhan30-Oct-15 1:38
professionalEr.Vaibhav Singh Chauhan30-Oct-15 1:38 
QuestionGood article. Pin
Member 935277525-Jul-14 10:58
Member 935277525-Jul-14 10:58 
GeneralGood Explanation Pin
Ismail4811-Aug-13 21:04
Ismail4811-Aug-13 21:04 
QuestionValidation Pin
Member 101973008-Aug-13 0:15
Member 101973008-Aug-13 0:15 
QuestionHow to sequence numbered the validation errors Pin
Rajiv Kr. Thakur19-Apr-13 20:48
professionalRajiv Kr. Thakur19-Apr-13 20:48 
GeneralMy vote of 5 Pin
Ronald.A28-Feb-13 7:41
Ronald.A28-Feb-13 7:41 
GeneralMy vote of 5 Pin
Abdul Rahman El Habboub10-Jan-13 3:17
Abdul Rahman El Habboub10-Jan-13 3:17 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh10-Nov-12 1:12
professionalRahul Rajat Singh10-Nov-12 1:12 
This article has been selected as Article of the Day on Microsoft's site http://www.asp.net/community[^] today(08 November 2012).

Rahul Rajat Singh
08 November 2012.

Every now and then say, "What the Elephant." "What the Elephant" gives you freedom. Freedom brings opportunity. Opportunity makes your future.

QuestionMy vote of 5 Pin
erkan islamovic20-Jun-12 22:42
erkan islamovic20-Jun-12 22:42 
GeneralMy vote of 4 Pin
BrianBissell9-Mar-12 3:32
BrianBissell9-Mar-12 3:32 
GeneralMy vote of 3 Pin
Dean Oliver22-Feb-12 8:38
Dean Oliver22-Feb-12 8:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.