ankitweblogic logo
W e b t u t o r i a l s

ASP.NET Tutorial


ASP.NET Introduction

ASP.NET Web Forms

Standard Controls

Label Control

TextBox Control

Image Control

Button Controls

Redirecting User

Using HyperLinks

RadioButton Control


CheckBox Control

CheckBoxList Control


ListBox Control

ImageMap Control

Master Page

View State

Event-Driven Programming


ASP.NET Page Structure

Visibility of Controls

Formatting Controls

Applying CSS

Dynamic CSS

Using Style Class

Themes and Skins

Panel Control

PlaceHolder Control

AdRotator Control

Calendar Control

Validation Controls

Page Navigation

User Control

Separating Code-Presentation

Overview of ADO.NET

Data Binding

DataBinding List Control

Validating Clients Data in Asp.Net

The data entered by the user in a user registration form needs to be checked to see that the user name is unique, the user satisfies the criteria for accessing the resources on that site and finally to enter the user data in a database on the server. Some users may fill the data incorrectly or submit incomplete forms. The site administrator must verify that forms are filled completely and correctly. This is where validation of user input becomes a vital necessity.

Client-Side Validation Vs. Server-Side Validation

Client-side logic has to be browser-specific though it is faster, more scalable and does not load the network or the server. Many browsers support style sheets and DHTML, which enable page content to be changed dynamically.

Performing the validation on the server-side removes the need to cater to different browsers but introduces delay in response, loads the server, reduces scalability, and increases network traffic.

ASP.NET Client-Side Validation: ASP.NET provides six validation controls
• RequiredFieldValidator
• CompareValidator
• RangeValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary

RequiredFieldValidator Control
This control is used to check that the user has entered a value in a mandatory field or not.

RequiredFieldValidator properties and methods are listed in a table. It has no events.
Property Description
ControlToValidate Specifies the ID of the control to be validated.
Display Sets how the error message contained in the Text property is displayed. Static (default), Dynamic, None.
EnableClientScript Enables or disables client-side form validation. By default, True.
Enabled Enables or disables both server and client-side form validation. By default, True.
ErrorMessage Specifies the error message that is displayed in the ValidationSummary control. It is displayed by the validation control when the Text property is not set.
InitialValue Gets or sets the initial value of the control being validated.
IsValid Is True when the validation check succeeds.
Text Sets the error message displayed by the control.
Property Description
Validate Performs validation and updates the IsValid property.

Example: RequiredFieldValidator Control

When the form is submitted, the page’s IsValid property is checked. This property is True if there is no error on the page. Otherwise, the user is shown with the error messages.

CompareValidator Control
This control is used to check the value of a control by comparing it with the value of another control in a form. You can set the data type of the values being compared and the operator to be used for comparison of values. For instance, you can check if the date of joining of an employee is greater than his date of birth or less than current date.

The properties and methods of the CompareValidator control are same as RequiredFieldValidator control. It has some additional properties which are shown in Table.
Property Description
ControlToCompare Specifies the ID of the control to use for comparing values.
ValueToCompare Specifies the value used when performing comparison.
Operator Gets or sets the comparison operator to use. Possible values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.
Type Gets or sets the data type to use when comparing values. Possible values are: String, Integer, Double, DateTime, and Currency.

Example: CompareValidator Control

Checking Data Type
The following example shows how you can use the CompareValidator control to check the data type of the value entered in a field. You can check whether the user has entered a date in a date field, a string in a string field, and a number in a number field by using the DataTypeCheck property of the validator control.

Example: Data Type Check

CompareValidator control requires date format as: 1/1/2002 or 1-1-2002.

RangeValidator Control
This control checks that the value in the control being validated falls within a specified range. The range can be specified using the attributes MinimumValue and MaximumValue. The values can be dates, numbers, or strings.

The properties and methods of the RangeValidator control are same as RequiredFieldValidator control. It has some additional properties which are shown in Table
Property Description
MaximumValue Specifies the maximum value in the range of permissible values.
MinimumValue Specifies the minimum value in the range of permissible values.

Example: Range Check using compare validator: The quantity of the ordered item must be between 10 and 100 kgs

Example: RangeValidator Control

RegularExpressionValidator Control
You can use this control to check whether a user has entered a valid e-mail address, telephone number, user name or password in a field.
The properties and methods of this control are same as RequiredFieldValidator control. This control has an additional property, ValidationExpression. This property is used to specify the regular expression to be used for performing validation.
Example: It requires the password field to contain only letters or digits. No special characters are allowed.

The following table summarizes the commonly used regular expressions:
Symbol Meaning
[abc] Matches any character in the set
[^abc] Excludes any character in the set
{N} N matches
{N,} N or more matches
{N,M} Between N and M matches
$ End of input text X$
. Any single character except the newline (\n) i.ation
* Zero or more matches ra*t
+ One or more matches ra+t
? Zero or one matches ra?t
\s Matches whitespace characters like, space, tab, new line etc. \sa
\S Matches any non-whitespace character \SF
\b Matches a backspace ion\b
\B Any position that isn’t a word boundary \BX\B
\d Matches any decimal character
\D Matches any non-decimal character
\t Matches a tab
\r Matches a carriage return
\n Matches a new line
\w Matches any alphanumeric character and underscore
\W Matches any non-word character

Examples of Regular Expressions
• Product code contains a single capital letter and 3 numerals: [A-Z][0-9]{3}
• To validate an email address: \S+@\S+\.\S{2,3}
• User names contain only alphanumeric characters or the underscore character, which consist of one or more word characters: \w+
• Password field contain between 8 and 30 characters: \w{8,30}
• You can validate a URL using the regular expression: http://\S+\.\S+
• A multi-line text box control does not have any MaxLength property. You can limit a user to 100 characters using the regular expression: .{0,100}
• Pin codes contain 6 digits: \d{6}
• In a similar manner you can check that telephone numbers.

ValidationSummary Controls

You can use the ValidationSummary control to present a summary of all the errors in a page at a single location.

This control has no methods or events. Its properties are listed in Table
Property Description
Display Sets the formatting for the error messages displayed by the control. Possible values are: BulletList (default), List, SingleParagraph.
EnableClientScript Enables or disables client-side form validation. By default, True.
Enabled Enables or disables both server and client-side form validation. By default, True.
HeaderText Sets the text that is displayed at the top of the summary of error messages.
ShowMessageBox When True, shows error messages in a pop-up message box.
ShowSummary Enables or disables the summary of error messages. By default, True.

Example 4.13: ValidationSummary Control

You can use the ValidationSummary control’s ShowMessageBox property to show error messages in a pop-up dialog box.

Using Validation Groups
If you added more than one form in a page, and both forms contained validation controls, the validation controls in both forms were evaluated regardless of which form you submitted.
For example, imagine that you wanted to create a page that contained both a login and registration form. If both forms included validation controls, submitting the login form caused any validation controls contained in the registration form to be evaluated.

Example 4.14: ShowValidationGroup Control

CustomValidator Control: If none of the validation controls support the validation requirements of an ASP.NET application, a custom validator control can be created. For Example, You can use validation control to check the user name and password of the user from a database, check if the user has enough funds in his/her bank account to purchase an item from your site. This validation will be performed entirely on the server-side.

The properties and methods of the CustomValidator control are same as RequiredFieldValidator control. It has some additional properties, methods and events which are shown below:
Property Description
ClientValidationFunction Specifies the name of the client-side validation function.
Method Description
OnServerValidate Raises the ServerValidate event.
Event Description
ServerValidate Represents the server-side validation function.

The ServerValidateEventArgs parameter has the following 2 properties:
• IsValid: When True, the validation check is successful.
• Value: Value of the control being validated.

The client-side validation subroutine is similar except that it is written in a scripting language. You can catch the validation subroutines to the CustomValidator control through the properties, ClientValidationFunction, and OnServerValidate.

Example CustomValidator Control: checks if the string entered in a textbox is a 8 character long or not.

Disabling Validation: Every form contains a Submit button to submit the details and a Cancel button that can be used to cancel the data entered by the user in the form. This is required if the user has changed his mind about filling the form and wishes to go to another page. Canceling the form when the form contains validation controls is not easy. You can get around this problem by using the CausesValidation property of the Button control. This property can be used to enable or disable validation when the button is clicked.

Example: Disabling Validation

You can disable client-side form validation by using the following page directive:

<%@ Page ClientTarget="DownLevel" %>
Set the EnableClientScript property to False.

This directive forces validation to be performed only on the server-side.