Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Validating User Input In ASP.NET 2.0 Web Applications

What you are going to learn in this tutorial?

What is Validation?
Why it's important?
How to use ASP.NET 2.0 validation controls
Why you cannot validate every possible input.

Introduction

Developing robust applications is the target of every serious developer. Being sure from the correctness of the input coming to your application is one of the major practices used to rise application robustness. In this tutorial we are going to give you the skills needed to build web applications that can detect and (sometimes) correct bad inputs from your users.

What you should already know?

What is controls, and their properties?
What is the behavior of server side controls?
The process of developing a very simple web application

What is input validation?

In most of web applications, the user of the application provides input to be manipulated by your web application. As the user is a human being, errors can occur while this input is being done. 'Input Validation' is a programming practice in which the developer of the web application attempts to detect incorrect user inputs and make his application act accordingly.

So, what all of this is about? We all like to skip into implementation!

Although it's not typically a good practice to skip into implementation without sufficient preparation, in the particular domain of our tutorial we can do so safely. In fact this will give you a bird view picture of the subject that will make the comprehension of the rest of the tutorial easier.

Example 1 (Download!)

In the following example we will provide you with step by step instructions regarding how to force your user to enter a value inside a text box (he will not be able to continue working without entering this value). The example is a very simple calculator that calculates the square of the number (the number multiplied by itself) entered by the user. Here's the steps you need to perform:
From the toolbox get a TextBox, a Label, a Button, and a RequiredFieldValidator and draw them on your form (Place the RequiredFieldValidator control to the side of the TextBox)
In the properties window, set the following properties:


Control Name Property Name Value
RequiredFieldValidator1 ControlToValidate TextBox1
RequiredFieldValidator1 ErrorMessage Must Enter A value!
Button1 Text Square
Label1 Text <Empty>


In the click event of our button type the following code:


Dim n As Integer
n =
Integer.Parse(TextBox1.Text)
Label1.Text = Str(n * n)


Run your application and click the button
Congratulations, you are now a user of an application that employ input validation, want to know why?
Simply click the 'Square' button without entering any values. You will notice that the square will not be calculated and a message will appear to side of the text box indicating that you must enter a value first.
Enter a numeric value in the text box and click the square button again, you will note that the error message will disappear and that the square will be calculated and shown in the label.


Why user input validation is important?

Any one of us once involved in developing a serious web application, knows very well that there are many reasons his application can fail. While writing the application, the scenarios of failure arise one by one and are to be handled by the developer so that his application is robust enough. If you asked any experienced developer about what most reduces these scenarios of failure, he will typically answer: "If just I'm sure the value of x is restricted to ..." Being sure from the characteristics of user input does not only reduce these scenarios of failure to a great extent, but also saves you from writing code to handle many cases of input because you are sure that these cases will never arise. It's 'Input Validation' what makes you that sure and lets you focus on the core of your application instead of wasting your time handling every case of input one by one.

Now, relax and let's start from scratch!

Thanks to ASP.NET 2.0, where you can find several controls that can be used to achieve the user input validation scheme we are talking about. Examples of these controls are: CompareValidator, CustomValidator, RangeValidator, RegularExpressionValidator, RequiredFieldValidator, and ValidationSummary. In this tutorial we will provide you with step by step instructions regarding how to utilize these control to benefit  from the validation features we mentioned before.

Can you validate everything?

Yes! only if you know exactly what will be the user input. Just kidding! No one (of course) can know exactly what will be the user input and if that happened then there is no need to make the user provide this input from the first place. This is the case, you cannot validate all types of user inputs.. Examples of inputs that cannot be validated are inputs that has no expected pattern (Example: An HtmlTextArea in which the user writes his opinion about your web site!). Although you can force the user to input a minimum number of characters in this example, you cannot (at least using the validation controls we present in this tutorial) check whether his input is meaningful or not.

How to think?

First of all, you have to decide what input you are going to validate. Please be more specific and ask yourself, what control and what property of that particular control I need to validate? To help you decide, here's a list of typical controls along with the typically validated property of this control.

Control Class Property that is typically validated
DropDownList Value
(of the SelectedItem member. i.e., SelectedItem.value)
HtmlInputFile Value
HtmlInputText Value
HtmlSelect Value
HtmlTextArea Value
ListBox Value
(of the SelectedItem member. i.e., SelectedItem.value)
RadioButtonList Value
TextBox Value

Below we list some validation controls along with the purpose(s) in which each of them can be used:

You need to ... Here's the validation control class you need!
We need to compare user input to another value (e.g., another property or constant) in a style similar to the old and ever lasting if statement. CompareValidator
Your validation needs does not fit on any of the categories specified in this table but you are still able to write code that checks for the validity of this input.
Here you can use the ValidateEmptyText property to do validation even if the validation value is empty. This is a new feature in ASP.NET 2.0
CustomValidator
You need to be sure whether the input falls between two bound (Example: User age must be between 18 and 99) RangeValidator

You need the input to follow a consistent pattern (Example: a phone number that must start with '+' and must be composed of 9 to 10 digits)

RegularExpressionValidator
You need to force the user to input a value inside a particular control and not to leave it empty. (Example: The User Name field in a login form) RequiredFieldValidator

So, how to use the validation controls in general?

As you may noted in Example 1.1, the general approach is to draw a validation control and associate it with the control to be validated via the validation control's ControlToValidate property.
Then to set the error message that to be displayed in case of error in the validation control's ErrorMessage property.
Some validation controls will need setting more properties as we will show in example 1.2
If you want to split the controls on your form into groups (with respect to validation), you can use the property ValidationGroup. This is a nice new feature in ASP.NET 2.0.

Example 2 (Download!)

Here we need the user to enter a value from 0 to 100 and we will show the associated grade, where 0 to 49 is associated with 'Poor', 50 to 70 is associated with 'Good', 71 to 90 is associated with 'Very Good', and 91 to 100 is associated with 'Excellent'. We will need to make sure that the user had entered a value and to ensure that this value is between 0 and 100.
From the toolbox get a TextBox, a Label, a Button, a RangeValidator, and a RequiredFieldValidator and draw them on your form (Place the RequiredFieldValidator control, and the RangeValidator control to the side of the TextBox)
In the properties window, set the following properties:


Control Name Property Name Value
RequiredFieldValidator1 ControlToValidate TextBox1
RequiredFieldValidator1 ErrorMessage Must Enter A value!
Button1 Text Square
Label1 Text <Empty>
RangeValidator1 ControlToValidate TextBox1
RangeValidator1 ErrorMessage Value must be between 0 and 100
RangeValidator1 MinimumValue 0
RangeValidator1 MaximumValue 100
RangeValidator1 Type Integer
RangeValidator1 SetFocusOnError True

In the click event of our button type the following code:

Dim n As Integer
n =
Integer.Parse(TextBox1.Text)
If n >= 0 And n <= 49 Then
    Label1.Text = "Poor"
ElseIf n >= 50 And n <= 70 Then
    Label1.Text = "Good"
ElseIf n >= 71 And n <= 90 Then
    Label1.Text = "Very Good"
Else
    Label1.Text = "Excellent"
End If


Run the example and note that it does not accept values outside 0 ... 100

Notes:

You may note that we set some properties that are specific to the validation control we used (like: MinimumValue, MaximumValue, Type). Of course different properties need to be used as we opt to use a different validation control)
In the last 'Else' statement we did not wrote a condition to check for 'n>=91 And n<=100' because we are sure that the RangeValidator will do so. This is what we said before that validation frees our mind from handling every possible scenario in our web application.
The property 'RangeValidator1.SetFocusOnError' was set to true so that the focus is automatically placed on the first control that has invalid input. This is a new feature in ASP.NET 2.0

For further information

Refer to the online copy of Microsoft Developers Network at http://msdn.microsoft.com or use you own local copy of MSDN.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |