You are on page 1of 57

ASP.

NET Technical Articles


User Input Validation in ASP.NET

Anthony Moore
Microsoft Corporation

July 2000
Updated March 2002

Summary: Provides a brief overview of the validation framework in ASP.NET and walks
through an example of adding validation to a page. (11 printed pages)

Contents:

Introduction
The Problem
The Objective
The Solution-Overview
Client Features
What Is a Validator?
Validator Walk-Through
It's Not Voluntary
Getting Regular
Comparing Apples and Apples
Custom Fit
The Finale
Sample Code

Introduction
Validating user input is a common scenario in a Web-based application. For production
applications, developers often end up spending a lot more time and code on this task than we
would like. In building the ASP.NET page framework, it was important to try and make the task
of validating input a lot easer than it has been in the past.

The Problem
In HTML 3.2, validating data is a difficult process. Each time you get a request, you need to
write code to check the input and write any errors the user has made back to the page to help the
user to correctly fill in the form. This is a taxing process for end users, developers, and servers
alike.

DTHML and scripting languages improve things somewhat. It is possible to provide the user
with immediate feedback on bad input and to prevent them from posting a page until it has been
corrected. However, it can be almost impossible to guarantee that every user of your site has the
required scripting environment. This usually means that if you want to use script to improve the
interface of your pages, you have to write the same validation logic twice, once on the client, and
again on the server, just in case the client script cannot be executed.

The Objective
Our objective with validation is as follows:

• Provide components that can perform 90 percent or more of the typical input validation
tasks for data entry pages.
• Have these components perform rich script-based validation on modern browsers that can
also effectively fall back to pure HTML 3.2 server-based validation, if required.
• Provide a flexible API so that any validation tasks not covered by the components are
easy to complete.

We visited a large number of real pages to determine the sort of scenarios these components
needed to be able to handle. We wanted to dramatically reduce the amount of validation code
needed for future applications.

The Solution—Overview
The validator controls are the main elements of the solution. A validator is a visual ASP.NET
control that checks a specific validity condition of another control. It generally appears to the
user as a piece of text that displays or hides depending on whether the control it is checking is in
error. It can also be an image, or can even be invisible and still do useful work. There are five
types of validator controls that perform different types of checks.

Another element in our solution is the ValidationSummary control. Large data entry pages
generally have an area where all errors are listed. The ValidationSummary automatically
generates this content by gathering it up from validator controls on the page.

The final element is the Page object itself. It exposes the all-important "IsValid" property, which
you check in server code to determine if all of the user input is OK.

Client Features
Most Web sites do all of their validation checks on the server. You need to write the server-based
checks anyway for clients without script, so it can be hard to justify writing it all over again for
rich clients.

Validation controls change all that, because almost all the duplicated logic is encapsulated in the
controls. If a client with Internet Explorer 4.0 or later uses your page, it can do the same input
validation that takes place on the server without you having to write any special client script.
The client side validation has a number of features:

• Errors can appear and disappear immediately after the bad input is entered/corrected.
This immediate feedback makes it much easier to correct bad input.
• Post-back is prevented if there are errors that are detectable on the client, saving the user
time and reducing hits on the server.
• The ValidationSummary updates itself without posting back if it detects errors.
• The ValidationSummary can optionally display a message box to the user if there are
errors.
• The client logic is all contained in a JScript library, so no ActiveX components or Java
applets are used.
• An object model is exposed on the client to allow enhancement of client-side validation
and behavior.

What Is a Validator?
In order to use validators effectively, it helps to have a firm definition of what they are. Let's
refine our previous definition a little:

"A validator is a control that checks one input control for a specific type of error condition and
displays a description of that problem."

This is an important definition, because it means that you frequently need to use more than one
validator control for each input control.

For example, if you want to check whether or not user input in a text box is (a) nonblank, (b) a
valid date between a particular range and (c) less than the date in another text input control, you
would want to use three validators. While this might seem cumbersome, remember that to be
helpful to the user, you would want to have three different text descriptions for all these cases.

The different types of validators are listed as follows:

RequiredFieldValidator Checks that the user has entered or selected anything.


Checks user input against a regular expression. This allows a wide
RegularExpressionValidator variety of checks to be made and can be used for things like ZIP
codes and phone numbers.
Compares an input control to a fixed value or another input control.
CompareValidator It can be used for password verification fields, for example. It is also
possible to do typed date and number comparisons.
Much like CompareValidator, but can check that the input is
RangeValidator
between two fixed values.
This allows you to write your own code to take part in the validation
CustomValidator
framework.

Validator Walk-Through
To demonstrate validation, we will walk through the process of adding validation to an existing
page. Here are some example requirements:

Write a web page to collect a new user id and password. The user id must contain 6-10 alpha
characters and must not already be in use. The password must contain 4-12 letters and at least
one of the characters "@#$%^&*/." The user must re-enter the password to make sure they
entered it correctly.

I am going to start with an HTML page that has been minimally converted to work with the
ASP+ page framework.

The process of converting the page includes the following steps:

1. Change the extension from ".html" or ".asp" to ".aspx".


2. Change the form and all the input tags to be "runat=server".
3. Use "ID" instead of "name".

Starting code:

<html>
<head>
<title>Validation Sample</title>
</head>
<body>

<form runat=server>
<p>Please enter a new User ID and Password:</p>
<table>
<tr>
<td>User ID:</td>
<td><input type=text runat=server id=txtName></td>
</tr>
<tr>
<td>Password:</td>
<td><input type=password runat=server id=txtPWord></td>
</tr>
<tr>
<td>Re-enter Password:</td>
<td><input type=password runat=server id=txtRePWord></td>
</tr>
<table><br>
<input type=submit runat=server id=cmdSubmit value=Submit>
</form>

</body>
</html>

Starting page:
It's Not Voluntary
The first thing we need to enforce is that the fields get filled in at all.

In front of each field, we add a RequiredFieldValidator. If the input field is blank, we want to
display an asterisk (*) in front of the field and report a text error in a summary area. Here is how
we add a RequiredFieldValidator to the User ID field:

<tr>
<td>
<asp:RequiredFieldValidator runat=server
ControlToValidate=txtName
ErrorMessage="User ID is required."> *
</asp:RequiredFieldValidator>
</td>
<td>User ID:</td>
<td><input type=text runat=server id=txtName></td>
</tr>

The * is displayed next to the label if the input is blank. The error message is reported in a
summary. The "ControlToValidate" property specifies the ID of the control to validate. The final
step is to add a validation summary to the top of the page like so:

<asp:ValidationSummary runat=server
HeaderText="There were errors on the page:" />

Here is how it looks on the page:


Getting Regular
Next we need to enforce the character requirements for the User ID and Password fields. For
these we will use RegularExpressionValidator controls. Regular expressions can be very
powerful in concisely expressing checks for this sort of information, as well as ZIP codes, phone
numbers, and e-mail addresses.

Here is how we specify the restrictions on User ID:

<td>
<input type=text runat=server id=txtName>
<asp:RegularExpressionValidator runat=server
ControlToValidate="txtName"
ErrorMessage="ID must be 6-10 letters."
ValidationExpression="[a-zA-Z]{6,10}" />
</td>

Note that in this case we did not specify any inner content within the tag. The inner text is
equivalent to the Text property of the control. If it is blank, the error message will be displayed
where the control is positioned, as well as appearing in the summary.

The password checks can be done with the following two validators. If you use more than one,
they must all match before the input is considered valid.

<asp:RegularExpressionValidator runat=server display=dynamic


ControlToValidate="txtPWord"
ErrorMessage="Password must contain one of @#$%^&*/."
ValidationExpression=".*[@#$%^&*/].*" />
<asp:RegularExpressionValidator runat=server display=dynamic
ControlToValidate="txtPWord"
ErrorMessage="Password must be 4-12 nonblank characters."
ValidationExpression="[^\s]{4,12}" />

Here is the form in action with the expressions:

Comparing Apples and Apples


We need to make sure the password re-entry field matches the password. We will use the
CompareValidator to do this, since it is capable of working with two input controls at a time:

<asp:CompareValidator runat=server
ControlToValidate=txtRePWord
ControlToCompare=txtPWord
ErrorMessage="Passwords do not match." />

By default, CompareValidator does a simple string match comparison. If required, it can do more
complex comparisons involving dates and numbers.

Custom Fit
The final thing we need to check is that the name is not already taken in our hypothetical site.
This is going to require looking at some data on the server. To simulate this, I will create a
dummy function in server-side code that checks that the first character is not an "a." The
following Visual Basic function is defined on the page:

<%@ Page Language="vb" %>


<script runat=server>

public sub CheckID(source as Object, args as ServerValidateEventArgs)


args.IsValid = args.Value.substring(0, 1).tolower() <> "a"
end sub

</script>
To call this function, I will add a CustomValidator, which is designed to call developer code to
perform its check. Here is the declaration:

<asp:CustomValidator runat=server
controltovalidate="txtName"
errormessage="ID is already in use."
OnServerValidate="CheckID" />

On a client with script, all the other validators do their checks on the client first before allowing
the submit to take place. If there are errors detected by server-only checks like this one, page will
be sent back to the user indicating those errors.

The Finale
Now, the only thing left is to make use of the nicely validated data. All you need to do is check
the IsValid property of Page to work out if you can proceed to update your database. Here is how
your submit handler might look:

public sub OnSubmit(source as Object, e as EventArgs)


if Page.IsValid then
' Now we can perform our transaction.
end if
end sub

As you can see, this handler will allow your data entry pages to consist of code that is specific to
your application instead of being full of code to deal with mundane input checking.

Here is some more of the final page in action:

Sample Code
<%@ Page Language="vb" %>
<script runat=server>

public sub CheckID(source as Object, args as ServerValidateEventArgs)


args.IsValid = args.Value.substring(0, 1).tolower() <> "a"
end sub

public sub OnSubmit(source as Object, e as EventArgs)


if Page.IsValid then
' Now we can perform our transaction.
end if
end sub

</script>
<html>
<head>
<title>Validation Sample</title>
</head>
<body>

<form runat=server>
<asp:ValidationSummary runat=server headertext="There were errors on the
page:" />

<p>Please enter a User ID and Password:</p>


<table>
<tr>
<td>
<asp:RequiredFieldValidator runat=server
controltovalidate=txtName
errormessage="User ID is required.">*
</asp:RequiredFieldValidator>
</td>
<td>User ID:</td>
<td>
<input type=text runat=server id=txtName>
<asp:RegularExpressionValidator runat=server display=dynamic
controltovalidate="txtName"
errormessage="ID must be 6-10 letters."
validationexpression="[a-zA-Z]{6,10}" />
<asp:CustomValidator runat=server
controltovalidate="txtName"
errormessage="ID is already in use."
OnServerValidate="CheckID" />

</td>
</tr>
<tr>
<td>
<asp:RequiredFieldValidator runat=server
controltovalidate=txtPWord
errormessage="Password is required.">*
</asp:RequiredFieldValidator>
</td>
<td>Password:</td>
<td>
<input type=password runat=server id=txtPWord>
<asp:RegularExpressionValidator runat=server display=dynamic
controltovalidate="txtPWord"
errormessage="Password must contain one of @#$%^&*/."
validationexpression=".*[@#$%^&*/].*" />
<asp:RegularExpressionValidator runat=server display=dynamic
controltovalidate="txtPWord"
errormessage="Password must be 4-12 nonblank characters."
validationexpression="[^\s]{4,12}" />
</td>
</tr>
<tr>
<td>
<asp:RequiredFieldValidator runat=server
controltovalidate=txtRePWord
errormessage="Re-enter password is required.">*
</asp:RequiredFieldValidator>
</td>
<td>Re-enter Password:</td>
<td>
<input type=password runat=server id=txtRePWord>
<asp:CompareValidator runat=server
controltovalidate=txtRePWord
controltocompare=txtPWord
errormessage="Passwords do not match." />
</td>
</tr>
</table><br>
<input type=submit runat=server id=cmdSubmit value=Submit
onserverclick=OnSubmit>
</form>
</body>
</html>

© Microsoft Corporation. All rights reserved.

ASP.NET Technical Articles

Validating ASP.NET Server Controls

By Bill Evjen
Reuters
December 2003

Applies to:
Microsoft® ASP.NET
Microsoft Visual Basic® .NET
Microsoft Visual C#® .NET

Summary: Learn how to use all the available ASP.NET validation server controls that are at
your disposal. This paper introduces these new controls and discusses tips and tricks on working
with them in practical scenarios. (34 printed pages)

Introduction
Looking at Validation
The RequiredFieldValidator Control
The CompareValidator Control
The RangeValidator Control
The RegularExpressionValidator Control
The CustomValidator Control
The ValidationSummary Control
Conclusion

Introduction
In your studies of ASP.NET, you might have been introduced to a number of different types of
controls, whether HTML server controls or Web server controls. This paper focuses on a series
of controls that stand out from the rest—validation server controls.

Validation server controls are a series of controls that help you validate the data that the user
enters into the other controls that are provided with ASP.NET. They determine whether the form
can be processed based upon the rules that you define in the validation server controls.

Looking at Validation
One of the most common elements of Web pages is a form in which the user can input data that
is posted back to the server. These forms are made up of different types of HTML elements that
are constructed using straight HTML, HTML server controls, or Web server controls. A variety
of HTML elements, such as text boxes, check boxes, radio buttons, drop-down lists and more,
can be used in forms.

Often when your ASP.NET applications are collecting information from a user, you want to
ensure that the data that you collect is valid. Some users are not interested in spending enough
time to enter the correct information into a form, and in some cases, users might even
intentionally enter false information to gain access or get past a certain step in your application's
workflow process.
One of the first steps is to understand what validating data means. Validating, in this case, does
not mean that if John Doe types his name into the form field of a text box as Fred Doe the
computer sends an alert to inform you that the data is untruthful. No, we still do not have the
capability to find out whether a statement is true.

Validation is testing to determine whether the user entered something into the field. After you
determine that something was entered, you can then also check to see whether what was entered
is a number or a character and if it is in the correct format. From there, you can compare user
input in different fields or against values that might be held in other repositories, such as a
database. You can check for many types of information, as you learn in the rest of this article.

Data collection on the Internet is one of its most important features, so you must make sure that
the data you collect has value and meaning. You ensure this by eliminating any chance that the
information collected does not abide by the rules you outline.

Understanding the Difference Between Server-Side and Client-


Side Validation

Many people new to ASP.NET don't know the difference between client-side and server-side
validation. You must understand these two different ways of validating the data users input into a
Web form.

After the user enters data into a Web form, clicks the Submit button, and sends the form data to
the server as a request, you can perform server-side validation on the data. If the data is incorrect
or not valid, you can send back a response stating this. If, however, when the user clicks the
Submit button, a scripting language that is part of the overall HTML page is initiated to check
the validity of the data before it is sent to the server, this is client-side validation.

It was a lot easier to understand the difference between these forms of validation when you
coded Active Server Pages 3.0 because, as the programmer, you personally performed almost all
data validation. You yourself either programmed it to be client-side or server-side.

When you used server-side validation with ASP 3.0, if something the user entered was wrong,
you could repost the form and ask the user to correct the information in that particular field of the
form. Sometimes, you carried the correct input from the other fields back to the form page, and
populated the fields for the users so they didn't have to re-enter the same information again.
Some sites on the Internet don't carry this inputted information back to the form page, and the
user is then required to enter all the information into the form a second time. Obviously, this may
cause people to leave your site for another.

The bad thing about server-side validation is that it requires trips back and forth to the server.
This takes a lot of resources and makes for a slower-paced form for the user. Nothing is more
annoying to a user who is on a dial-up connection than clicking the Submit button on the form
and then waiting for 20 seconds to find out that they didn't enter their password correctly.
The other option for form validation is to put some client-side JavaScript or VBScript at the top
of the ASP page that checks if the information in the fields is correct. This takes care of the
problem of making unnecessary trips to the server, but it requires another language to learn and
manage. JavaScript is a great language, but takes a lot of time to master, and there are always
problems getting your JavaScript code to work on different browsers. Listing 1 shows you an
example of using client-side JavaScript to perform form validation.

Listing 1: Client-side JavaScript for form validation

<script language="javascript">
<!--
Function CheckForm(form)
{
for(var intCtr = 0; intCtr <= (form.elements.length - 5); ++intCtr)
{
var temp = form.elements[intCtr];
if(temp.type == "text" && temp.value == "")
{
alert("Please Enter All Information!");
temp.focus();
return false;
}
}
return true;
}
//-->
</script>

This sample piece of JavaScript does some validation, but it doesn't check for all the in-
formation that you might need on the form you are building. This piece of code determines only
whether the user entered anything at all in all five fields within the form. It does not determine
whether the user entered an actual e-mail address within the e-mail address text box, whether the
user entered a number between two given numbers, or whether the password and the confirm
password text boxes match. After awhile, you can see that you need many JavaScript functions
to obtain the level of form validation required.

.NET to the Rescue!

Developers who used classic Active Server Pages 3.0 to develop Web pages might remember
that they used to spend a considerable amount of their time developing validation mechanics in
their pages. It was time consuming if you did it right. It was most efficient to do the validation of
the form on the client-side to limit the number of requests and responses required to work
through an application. As I stated, however, you were never quite sure if the requesting browser
would understand the scripting code that you used for the validation. So, it was usually better,
especially for critical Web applications, to bring the validation to the server.

ASP.NET has changed this by giving you the capability to use the validation server controls that
are provided with the other new controls at your disposal. What makes these validation server
controls effective is that when an ASP.NET page containing these controls is requested, it is the
ASP.NET engine that decides whether to perform the validation on the client or on the server
depending on the browser that is making the request. Therefore, your page's functionality
changes depending on the requesting browser—thus enabling you to make your Web pages the
best they can possibly be—rather than dummying-down your Web applications for the lowest
common denominator.

Validation server controls are the only type of ASP.NET server controls that also generate client-
side script. All the other controls work with the idea of making postbacks to the server (a request
to the server to get a response).

Presently, six different validation server controls are available for ASP.NET:

• RequiredFieldValidator
• CompareValidator
• RangeValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary

You can also customize validation for your own needs. Then, if there are any errors in the form
data, these validation server controls enable you to customize the display of error information on
the browser.

You place validation server controls on your page as you would any other type of controls. After
the user submits the form, the user's form information is sent to the appropriate validation
control, where it is evaluated. If the information doesn't validate, the control sets a page property
that indicates this. After all the form information is sent to all the validation server controls, if
one or more of the validation server controls cannot validate the information sent to it, the entire
form input is found to be invalid, and the user is notified.

Table 1 describes each of the six validation server controls.

Table 1: Available validation server controls

Validation Server
Description
Control

RequiredFieldValidato
Ensures that the user does not skip a form entry field
r

Allows for comparisons between the user's input and another


CompareValidator item using a comparison operator (equals, greater than, less
than, and so on)

Checks the user's input based upon a lower- and upper-level


RangeValidator
range of numbers or characters
Checks that the user's entry matches a pattern defined by a
RegularExpressionVali
regular expression. This is a good control to use to check e-
dator
mail addresses and phone numbers

CustomValidator Checks the user's entry using custom-coded validation logic

Displays all the error messages from the validators in one


ValidationSummary
specific spot on the page

Not all button clicks are equal

Normally, in a series of HTML form elements, there is some sort of Button, ImageButton, or
LinkButton control on the page that submits the form and causes the validation to initiate. This
might not be the functionality that you are always looking for in your Web forms. You may not
want each and every button on the ASP.NET page to initiate validation.

For instance, you might have a Cancel or Reset button on the Web page. If the user clicks one of
these buttons, you don't want that button click to validate the contents contained in the Web
form.

To prevent this, you have to set the CausesValidation property for the control to False.

<asp:Button id="Button1" runat="server" Text="Button"


CausesValidation="False"></asp:Button>

The RequiredFieldValidator Control


The RequiredFieldValidator server control makes sure that the user enters something into the
field that it is associated with in the form. You need to tie the RequiredFieldValidator to each
control that is a required field in the form. Although this is the simplest of the validation server
controls, you must understand certain things about it.

To see an example of using the RequiredFieldValidator server control, create a Web form that
contains a TextBox server control and a Button server control. Next to the button, place a
RequiredFieldValidator server control. Your ASP.NET page should look like the code illustrated
in Listing 2.

Listing 2: Using the RequiredFieldValidator control

Visual Basic .NET

<%@ Page Language="VB" %>


<script runat="server">

Sub Button1_Click(sender As Object, e As EventArgs)


Label1.Text = "Page is valid!"
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
&nbsp;
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server"
ErrorMessage="Required!"
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Visual C# .NET

<%@ Page Language="C#" %>


<script runat="server">

void Button1_Click(Object sender, EventArgs e) {


Label1.Text = "Page is valid!";
}

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
&nbsp;
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server"
ErrorMessage="Required!"
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Run this page and then omit putting a value in the text box. When you click the button, you get a
result similar to that shown in Figure 1.

Figure 1: Causing the RequiredFieldValidator server control to fire

There are a few things to be aware of when using the RequiredFieldValidator server control in
your ASP.NET pages. First of all, the most important property of this validation control is the
ControlToValidate property. The value assigned to this control needs to be the value of the id
property for the control to which you want to link the RequiredFieldValidator control. You can
link only one RequiredFieldValidator server control to any other server control on the page. For
instance, if you have three required TextBox controls on your ASP.NET page, you need three
separate RequiredFieldValidator controls to make sure that they are all required.

The second property of this control is the ErrorMessage property. This is the text that appears
where the RequiredFieldValidator control is located on the ASP.NET page if the TextBox is left
empty. Instead of using the ErrorMessage property, you can also use the Text property:

<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" Text="Required!"
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>

Or you can use the following construct:


<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1">
Required!
</asp:RequiredFieldValidator>

As you run this simple page, notice a few things. First of all, if you are running a client that is
considered an upper-level browser (for example, Internet Explorer 4.0 or better), the code
generated to perform the validation is client-side. To see this, right-click the page, and then click
View Source. You see JavaScript in the code of the page.

The JavaScript in the code of the page means that the required field checking against the text box
on the page is done client-side. To test this, simply click the button on the page, and you see the
Required! error message displayed. Next, enter a value in the TextBox control, and then press
TAB. The RequiredFieldValidator server control is then triggered.

By default, red text is used for the error messages that are shown by these validation server
controls. As with most of the ASP.NET server controls, however, you can change the style of the
controls by changing the properties of the control in code or within the designer. For instance,
you can apply a more complex style as illustrated here:

<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1" BackColor="DarkGray"
BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
ForeColor="White" Font-Bold="True" Font-Names="Verdana"
Font-Size="X-Small">&nbsp;Enter something&nbsp;
</asp:RequiredFieldValidator>

Using code similar to the preceding, you can get a more elaborate result, as shown in Figure 2.

Figure 2: A RequiredFieldValidator control with a little more style


Note The RequiredFieldValidation server control works with most HTML form
elements except for check boxes. You cannot validate against the CheckBox or
CheckBoxList server controls using the RequiredFieldValidator server control.
Instead you need to use the CustomValidator server control. An example of this is
shown later in this article.

Double-Checking Client-Side Validation

One interesting point is that even though the form data is validated on the client (eliminating the
need for additional requests to and responses from the server to validate the data), the data
entered is re-verified on the server. After the data is checked on the client and found valid, it is
rechecked on the server using the same validation rules. These are rules that you establish to
ensure against some tricky programmer out there trying to bypass the validation process by
posting the page to the server as if it passed validation.

Using the InitialValue Property with a TextBox Server Control

Another property to be aware of when working with the RequiredFieldValidator server control is
the InitialValue property. Instead of being empty, HTML form elements can be populated
with default values. In this case, you expect the user to change the value in these elements.

This situation is illustrated in the Listing 3, which shows a TextBox server control with an
associated RequiredFieldValidator server control.

Listing 3: A TextBox control with a default value

<asp:TextBox id="TextBox1" runat="server">Hello</asp:TextBox>


&nbsp;
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Please change value"
ControlToValidate="TextBox1" InitialValue="Hello">
</asp:RequiredFieldValidator>

In this example, the single text box has a default value of Hello. The value you place here can be
from any source, even a dynamic source. There is also a RequiredFieldValidator server control
that is assigned to validate this text box. In this case, you want the user to change the initial value
of this control to something other than the default value of the InitialValue property —Hello.
You can also populate the value of this property from a dynamic source, just as you can populate
the TextBox server control from a dynamic source.

RequiredFieldValidator1.InitialValue = some value

Because of the InitialValue property, if the user tries to submit the form without changing the
value in the text box, the RequiredFieldValidator control fires and the form does not post to the
server. If the user changes the value in the text box and submits the form, this
RequiredFieldValidator control does not fire and the form is posted.
Requiring a Value Change and Disallowing Empty Values at the
Same Time

When using the RequiredFieldValidator control against a text-based control such as a TextBox
control, you can use the InitialValue property. The form validation fails if the value contained
in the associated control is not changed from this value. If you use this kind of construct,
however, the user can change the value of the text box in any manner to get past the validation.
He or she can even empty the text box of any value, and it still passes the validation process.

In some situations, you can require the user not only to change the initial value of the text box,
but also to input some value so that it is not empty. To do this, use two RequiredFieldValidator
server controls. The first RequiredFieldValidator server control uses the InitialValue property
to ensure that the user changes the default value in the text box that the control is associated
with. The second RequiredFieldValidator control validates that the same text box is not left
empty, as illustrated in Listing 4.

Listing 4: A single TextBox control with two RequiredFieldValidator controls

<asp:TextBox id="TextBox1" runat="server">Hello</asp:TextBox>


&nbsp;
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Please change value"
ControlToValidate="TextBox1" InitialValue="Hello">
</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator id="RequiredFieldValidator2"
runat="server" ErrorMessage="Do not leave empty"
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>

Using the InitialValue Property with a DropDownList Control

A good way of using the InitialValue property is with the DropDownList server control. For
instance, a drop-down list might have a default value that is not an empty value (by default, some
text appears in it). An example of a drop-down list with the RequiredFieldValidator that uses the
InitialValue property is illustrated in Listing 5.

Listing 5: Using the RequiredFieldValidator server control with the Drop-DownList server
control

<asp:DropDownList id="DropDownList1" runat="server">


<asp:ListItem Selected="True">Select a profession</asp:ListItem>
<asp:ListItem>Programmer</asp:ListItem>
<asp:ListItem>Lawyer</asp:ListItem>
<asp:ListItem>Doctor</asp:ListItem>
<asp:ListItem>Artist</asp:ListItem>
</asp:DropDownList>
&nbsp;
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Please make a selection"
ControlToValidate="DropDownList1"
InitialValue="Select a profession">
</asp:RequiredFieldValidator>

Using this kind of construct enables you to place a description of the actions required in the
drop-down list and also requires the user to make a selection from the choices. To get past the
validation process, the user must make a selection other than the Select a profession choice.
If the user doesn't enter a profession, an error message is returned (see Figure 3). It takes a lot of
code to write your own JavaScript function for this procedure, and that JavaScript also has to be
browser-independent. With ASP.NET, the RequiredFieldValidator server control takes care of
that.

Figure 3: Validation error based upon the DropDownList control

The CompareValidator Control


The CompareValidator server control compares the value entered into the form field to another
field, a database value, or other value that you specify. When comparing against data types, you
just set the Operator—DataTypeCheck. After that is done, you can set the Type attribute to
String, Integer, Double, Date, or Currency in the CompareValidator control to make sure that
the user's input into the field is the specified type.

Validating Against Other Controls on the Web Form

Using the CompareValidator server control, you can make comparisons between different
controls within a form on your ASP.NET page. For example, if you want to compare what the
user enters in the Password field to the entry in the Confirm Password field to see whether they
are the same, you can use the CompareValidator server control. Using these two fields is a
common practice when a form asks for a password. It ensures that the user doesn't mistype the
password (see Listing 6).

Listing 6: Using the CompareValidator server control

Visual Basic .NET

<%@ Page Language="VB" %>


<script runat="server">

Sub Button1_Click(sender As Object, e As EventArgs)


Label1.Text = "Passwords match"
End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Password<br>
<asp:TextBox id="TextBox1" runat="server"
TextMode="Password"></asp:TextBox>
&nbsp;
<asp:CompareValidator id="CompareValidator1"
runat="server" ErrorMessage="Passwords do not match!"
ControlToValidate="TextBox2"
ControlToCompare="TextBox1"></asp:CompareValidator>
</p>
<p>
Confirm Password<br>
<asp:TextBox id="TextBox2" runat="server"
TextMode="Password"></asp:TextBox>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Login"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Visual C# .NET

<%@ Page Language="C#" %>


<script runat="server">

void Button1_Click(Object sender, EventArgs e) {


Label1.Text = "Passwords match";
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Password<br>
<asp:TextBox id="TextBox1" runat="server"
TextMode="Password"></asp:TextBox>
&nbsp;
<asp:CompareValidator id="CompareValidator1"
runat="server" ErrorMessage="Passwords do not match!"
ControlToValidate="TextBox2"
ControlToCompare="TextBox1"></asp:CompareValidator>
</p>
<p>
Confirm Password<br>
<asp:TextBox id="TextBox2" runat="server"
TextMode="Password"></asp:TextBox>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Login"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

In this example, the Web form uses two TextBox server controls. One is for the user to enter the
password, and the second TextBox control requires the user to enter the password again to ensure
they didn't mistype the original. By using the CompareValidator server control, you guarantee
that they are equal strings. If they are not equal, the page returns an error message (see Figure 4).
If they are equal, your page submits as valid.
Figure 4: In this example, the user mistyped the password and got an error message.

Validating Against Constants

You can also use the CompareValidator server control to make sure that the value typed into the
form field by a user is valid when compared against a constant, some dynamic value that you
retrieve, or that it adheres to a specific data type. Listing 7 shows an example of this.

Listing 7: Checking to make sure value entered is of a specific data type

Age:
<asp:TextBox id="TextBox1" runat="server" MaxLength="3">
</asp:TextBox>
&nbsp;
<asp:CompareValidator id="CompareValidator1" runat="server"
ErrorMessage="You must enter a number"
ControlToValidate="TextBox1" Type="Integer"
Operator="DataTypeCheck"></asp:CompareValidator>

In this example, the user must enter an integer in the text box; otherwise, the CompareValidator
server control fires and displays an error message on the page. By giving the Type property of
the CompareValidator server control a value of Integer, you ensure that the value entered in the
text box conforms to this .NET Framework data type.

You also have the option of not only comparing values against specific data types, but also
ensuring that values are valid when compared against certain constants (see Listing 8).

Listing 8: Comparing values against constants for validity


Age:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:CompareValidator id="CompareValidator1" runat="server"
Operator="GreaterThan" ValueToCompare="18"
ControlToValidate="TextBox1" ErrorMessage="You must be older than
18 to join" Type="Integer"></asp:CompareValidator>

In this case, a few checks are made against any value that the user types in the text box. The first
is based on the Type property in the CompareValidator server control. The Type property has the
value of Integer, therefore any value placed in the text box needs to conform to this .NET
Framework data type. If the user enters a string into the text box, the form submission is
invalid. The next property is the Operator property. This property has a value of GreaterThan,
meaning that for the form submission to be valid, the value entered in the text box has to be
greater than the value that is assigned to the ValueToCompare property. For this
CompareValidator server control, the ValueToCompare property has a value of 18. This means
that the value entered in the text box on the page must be an integer greater than 18. If it does
not meet these criteria, the value is considered invalid, and the CompareValidator server control
displays an error message in the browser.

In the situation shown in Listing 8, you are not comparing two fields in the form; instead, you are
comparing one field against a value that you have specified in code. The Operator property can
contain one of the following values:

• Equal
• NotEqual
• GreaterThan
• GreaterThanEqual
• LessThan
• LessThanEqual
• DataTypeCheck

The RangeValidator Control


The RangeValidator server control is similar to the CompareValidator server control, but the
RangeValidator server control compares what is entered into the form field with two values and
makes sure that what was entered by the user is between these two specified values.

For instance, imagine that you have a text box where you want end users to enter their ages.
Instead of being greater than or less than a specific constant, you want the values entered to be
between a specific range of numbers. For this, you use the RangeValidator server control, as
illustrated in Listing 9.

Listing 9: Using the RangeValidator server control to work with a range of numbers

Age:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:RangeValidator id="RangeValidator1" runat="server"
ControlToValidate="TextBox1" Type="Integer"
ErrorMessage="You must be between 30 and 40"
MaximumValue="40" MinimumValue="30"></asp:RangeValidator>

In this case, the user should enter a value between 30 and 40 in the text box. If some number is
entered that is outside of this range, the RangeValidator server control fires an error message and
considers the form submission invalid.

The Type property enables you to make comparisons against many different .NET Framework
types, such as String, Integer, Double, Date, and Currency. These choices enable you to do a
number of range comparisons. For instance, you can use the Currency value in the Type
property to retrieve monetary-value entries that are within a certain range. You can also use the
Date value for the Type property to make sure that the entry is between specific date ranges.

Also, just as you can use the String data type in the CompareValidator server control, you can
use the String data type with the RangeValidator server control to make sure that the value
entered falls within a specific range of characters. For example, if the user is entering her last
name, and you want only people with last names starting with M and P to proceed, you can
easily do this by using the RangeValidator server control, as illustrated in Listing 10.

Listing 10: Comparing an entry to a range of characters

Last name:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:RangeValidator id="RangeValidator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Your last name needs to be between M and P"
MaximumValue="Q" MinimumValue="M"></asp:RangeValidator>

In the example in Listing 10, the value is being checked against a range that is specified by using
the MaximumValue and MinimumValue properties. Notice, in this example, that the Type property
is not specified. In this case, it doesn't need to be specified because the default value of the Type
property is String. If not specified, it is considered to have the value of String.

The RegularExpressionValidator Control


The RegularExpressionValidator server control is a validation control that enables you to check
the user's input based on a pattern defined by a regular expression. This is a great control to
check whether the user has entered a valid e-mail address or telephone number. In the past, these
kinds of validations took a considerable amount of JavaScript coding. The
RegularExpressionValidator control with ASP.NET saves coding time.

In the Properties window for the RegularExpressionValidator server control, click the button in
the ValidationExpression box, and Visual Studio.NET provides you with a short list of
expressions to use in your form via the Regular Expression Editor. However, you are not limited
to these regular expressions in your ASP.NET applications. The list of prepared expressions is
shown in Figure 5.

Figure 5: The Regular Expression Editor

For an example of using the RegularExpressionValidator server control to make sure that a value
entered in a text box is an e-mail address, look at Listing 11.

Listing 11: Validating an e-mail address

Email:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="You must enter an email address"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>

In this example, notice that you place the Internet e-mail address regular expression in your
ValidationExpression property. The great thing is that it is pretty simple, and it takes hardly
any coding. Figure 6 shows the error message that results if a user enters an incorrect e-mail
address in the text box.
Figure 6: Validating whether an e-mail address is entered in a text box

Note The e-mail address is checked only to see whether it is in the correct format.
The e-mail address is not checked in to ensure that it is an actual e-mail address.

A great place on the Internet to find free regular expressions is the RegEx Library at
RegExLib.com.

Using Images for Your Error Messages

One interesting way of showing your error messages when using validation controls is to use
images along with text for identifying errors on your ASP.NET pages. This secret is not limited
to the RegularExpressionValidator server control, but can be used with all the validation server
controls.

To use an image instead of text for your error messages, you create something similar to the code
in Listing 13.

Listing 13: Using images for your validation messages

Email:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage='<img src="error.gif">'
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>

To use an image instead of text for your error messages, you use an HTML string that points to
the image that you want to display for the value of the ErrorMessage property (see Figure 7).
Figure 7: An image is displayed when the incorrect e-mail address is entered.

The CustomValidator Control


You are not limited to the validation controls that have been shown thus far in this article; you
also have the CustomValidator server control. The CustomValidator server control enables you
to develop your own custom server-side or client-side validations. At times, you may want to
compare the user's input to a value in a database, or to determine whether his input conforms to
some arithmetic validation that you are looking for (for instance, if the number is even or odd).
You can do all this and more by using this type of validation control.

Client-side Validation

One of the cool things about using the validation controls, in general, is that they allow for
client-side validation of certain HTML server controls. As I said, you can create your own
JavaScript functions that provide you with a higher level of validation capabilities.

Listing 14 illustrates how to use JavaScript and the CustomValidator server control to expand
upon the default validation capabilities that are provided to you with the .NET Framework.

Listing 14: Creating your own client-side validation functions

Visual Basic .NET

<%@ Page Language="VB" %>


<script runat="server">

Sub Button1_Click(sender As Object, e As EventArgs)


Label1.Text = "VALID NUMBER!"
End Sub
</script>
<html>
<head>
<script language="JavaScript">
function validateNumber(oSrc, args) {
args.IsValid = (args.Value % 5 == 0);
}
</script>
</head>
<body>
<form runat="server">
<p>
Number:
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="Number must be divisible by 5"
ClientValidationFunction="validateNumber">
</asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Visual C# .NET

<%@ Page Language="C#" %>


<script runat="server">

void Button1_Click(Object sender, EventArgs e) {


Label1.Text = "VALID NUMBER!";
}

</script>
<html>
<head>
<script language="JavaScript">
function validateNumber(oSrc, args) {
args.IsValid = (args.Value % 5 == 0);
}
</script>
</head>
<body>
<form runat="server">
<p>
Number:
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="Number must be divisible by 5"
ClientValidationFunction="validateNumber">
</asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

The important part of the CustomValidator server control here is the


ClientValidationFunction property. The value of this property must be the client-side
JavaScript function that is in the page—in this case, the validateNumber function. By simply
using this with the ClientValidationFunction property, you have tied the validation process
to the custom client-side function that you created, as illustrated in Figure 8.

Figure 8: Performing a custom client-side validation using the CustomValidator server


control

You set the args.IsValid property to either True or False in the JavaScript function. The
args.Value property is the value from the user that is retrieved from the control that the
CustomValidator server control is tied to.

Using the ClientValidationFunction property enables you to incorporate your own JavaScript
functions into ASP.NET controls so that they behave like the other validation controls.
Server-side Validation

The other way of performing validation on Web forms using the CustomValidator server control
is to use server-side validation. This is just as easy as the client-side validation.

Server-side validation of your Web forms enables you to create rather elaborate validation
capabilities. Listing 15 shows you a not-too-elaborate example of server-side checking. Here the
code determines whether the number entered in the text box on the ASP.NET page is even.

Listing 15: Creating your own server-side validation functions

Visual Basic .NET

<%@ Page Language="VB" %>


<script runat="server">

Sub Button1_Click(sender As Object, e As EventArgs)


If Page.IsValid Then
Label1.Text = "VALID ENTRY!"
End If
End Sub

Sub ValidateNumber(sender As Object, args As ServerValidateEventArgs)


Try
Dim num As Integer = Integer.Parse(args.Value)
args.IsValid = ((num mod 5) = 0)
Catch ex As Exception
args.IsValid = false
End Try
End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Number:
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="Number must be divisible by 5"
OnServerValidate="ValidateNumber"></asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Visual C# .NET

<%@ Page Language="C#" %>


<script runat="server">

void Button1_Click(Object sender, EventArgs e) {


if (Page.IsValid) {
Label1.Text = "VALID ENTRY!";
}
}

void ValidateNumber(object source, ServerValidateEventArgs args)


{
try
{
int num = int.Parse(args.Value);
args.IsValid = ((num%5) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Number:
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="Number must be even"
OnServerValidate="ValidateNumber"></asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
Performing custom server-side validation with the CustomValidator server controls requires that
you use the OnServerValidate property instead of the ClientValidationFunction property.
The ClientValidationFunction is used with the CustomValidator server control when
working with client-side validation.

In this case, you need to give the OnServerValidate property a value that is equal to the name
of the server-side function that you would write in one of the .NET-compliant languages.

Making Validation More Secure

If you are going to use the CustomValidator server control for client-side validation, you should
also consider re-evaluating the user's input using a server-side validation function.

It is not too hard for some people to post a form back to your server and bypass or fool the client-
side validation. If you re-evaluate the input on the server, you can stop this from occurring,
making your ASP.NET applications more secure.

Using the CustomValidator server control to validate the Checkbox server control

If you have been working through the examples so far in this article, note that there wasn't a
validation server control in place that was able to validate the CheckBox server control. Don't be
too worried. You can use the CustomValidator server control to work through this control. You
can use it any time that a validation server control on your page is not using the
ControlToValidate property. For an example of this, see Listing 16.

Listing 16: Validating a check box

Visual Basic .NET

<%@ Page Language="VB" %>


<script runat="server">

Sub CustomValidator1_ServerValidate(source As Object, _


args As ServerValidateEventArgs)

args.IsValid = (CheckBox1.Checked = True)


End Sub

Sub Button1_Click(sender As Object, e As EventArgs)


If Page.IsValid Then
Label1.Text = "Thank you for your donation!"
Else
Label1.Text = ""
End If
End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Check checkbox if you want to donate $10
</p>
<p>
<asp:CheckBox id="CheckBox1" runat="server"
Text="Donate $10"></asp:CheckBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Please donate $10"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Submit"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Visual C# .NET

<%@ Page Language="C#" %>


<script runat="server">

void CustomValidator1_ServerValidate(Object source,


ServerValidateEventArgs args) {

args.IsValid = (CheckBox1.Checked == true);


}

void Button1_Click(Object sender, EventArgs e) {


if (Page.IsValid) {
Label1.Text = "Thank you for your donation!"; }
else {
Label1.Text = "";
}
}

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Check checkbox if you want to donate $10
</p>
<p>
<asp:CheckBox id="CheckBox1" runat="server"
Text="Donate $10"></asp:CheckBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Please donate $10"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Submit"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Note that a CheckBox server control appears on the page. Also notice that there isn't a validation
server control on the page that has this CheckBox server control tied to it via any property
settings. Instead, a CustomValidator server control on the page references a server-side function
called CustomValidator1_ServerValidate.

Within this server-side function, validation performed in the code checks whether the CheckBox
server control's Checked property has a value of True (meaning that it is checked). If the value
of this property is True, the CustomValidator server control is passed a True value—meaning
that the input passed the test.

The CustomValidator server control enables you to do almost any type of validations that you
can think of. This is a great control to use if you do any database validations on the input that is
entered into a form by a user. This control can also apply any complicated logic that you want to
include in the validation process.

The ValidationSummary Control


The ValidationSummary server control works with all the validation server controls on the page.
It takes all the error messages that the other validation controls send back to the page and puts
them all in one spot (that you specify) on the page. These error messages can be displayed in a
list, bulleted list, or paragraph.

Showing a Bulleted List of Errors

You can use the ValidationSummary server control in a number of ways, but the example in
Listing 17 shows you how to use it in a simple manner. For this example, two text boxes on the
page are associated with a RequiredFieldValidator control. When an error is triggered, not only
does it display the error next to the text box itself, it also displays it in a summary at the bottom
of the ASP.NET page.

Listing 17: Having a summary of errors appear on the screen


<p>First name
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="You must enter your first name"
ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
</p>
<p>Last name
<asp:TextBox id="TextBox2" runat="server"></asp:TextBox>
&nbsp;
<asp:RequiredFieldValidator id="RequiredFieldValidator2"
runat="server" ErrorMessage="You must enter your last name"
ControlToValidate="TextBox2"></asp:RequiredFieldValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click" runat="server"
Text="Submit"></asp:Button>
</p>
<p>
<asp:ValidationSummary id="ValidationSummary1" runat="server"
HeaderText="You received the following errors:">
</asp:ValidationSummary>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>

Using this kind of construct, when the validation server control is triggered, error messages
similar to the ones shown in Figure 9 appear on the screen.
Figure 9: Validation errors shown using the ValidationSummary server control

By default, the ValidationSummary server control shows the errors in a bulleted list on the page
using red text. You have the option to completely alter how output displays in the browser.

To change how the error messages are displayed, you can change the value of the DisplayMode
property of the ValidationSummary control. The possible values of this control can be set to the
following:

• BulletList
• List
• SingleParagraph

If you use the BulletList value for the DisplayMode property, it appears as shown in Figure
11. If you use List, it appears without bullets. If you use SingleParagraph, the errors appear in
a text area all on one line in a single paragraph.

Showing a Dialog Box Containing Error Notifications

One flexible feature of the ValidationSummary server control is that you can easily show the
ASP.NET page's errors in a pop-up dialog box. You have the option of showing the summary in
the browser and the dialog box together, or just in the dialog box.
The property that controls whether the message appears in the browser is the ShowSummary
property. To turn off the display of validation errors in the browser, set the value of the
ShowSummary property to False. To show validation errors in a dialog box, set the
ValidationSummary control's ShowMessageBox property to True (see Listing 18).

Listing 18: Showing errors in a dialog box

<asp:ValidationSummary id="ValidationSummary1" runat="server"


ShowMessageBox="True" ShowSummary="False"></asp:ValidationSummary>

This code produces results similar to those in Figure 10.

Figure 10: A dialog box showing the page's validation errors

Understanding the Difference Between the ErrorMessage and


Text Properties

In the examples shown so far using the ValidationSummary server control, the error messages
were next to the items that were being validated (the RequiredFieldValidator server controls) and
were displayed within the ValidationSummary server control. One ideal way of presenting this
validation-error information is to have an asterisk (*) appear next to the HTML form fields in
question, while the error messages stating what is wrong with the input appear in the list of errors
shown within the ValidationSummary control.

To accomplish this, you use the specific validation controls—not the ValidationSummary server
control itself. For instance, if there is a RequiredFieldValidator server control validating a text
box, you construct this validation control as shown in Listing 19.
Listing 19: Showing text differently than it is displayed in the ValidationSummary server
control

<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="You must enter your first name"
ControlToValidate="TextBox1">*</asp:RequiredFieldValidator>

Or:

<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="You must enter your first name"
ControlToValidate="TextBox1" Text="*">
</asp:RequiredFieldValidator>

By constructing the page's validation server controls, as shown here, using different values for
the ErrorMessage and Text properties, you get a result similar to that shown in Figure 11.

Figure 11: Using different text for the validation error messages

When both the ErrorMessage and Text properties are used for the validation controls, the value
of the ErrorMessage property is displayed in the ValidationSummary server control's listing of
validation errors, and the value assigned to the Text property is displayed in the validation
control itself.
Conclusion
You can do a lot with validation, far more than this article explains. Validation controls make a
developer's life a lot easier. (To develop the same type of functionality in the past, a developer
had to sometimes go to extreme JavaScript-coding measures.)

The powerful thing about using these validation controls is that they are easy to implement.
Modifying them is a piece of cake, so you can easily check for all sorts of parameters on the
input generated from your forms.

Validation and Web controls make an outstanding combination for building smart forms.

About the Author

Bill Evjen is an active proponent of .NET technologies and community-based learning initiatives
for .NET. He is a technical director for Reuters, the international news and financial services
company based in St. Louis, Missouri. Bill is the founder and executive director of the
International .NET Association (INETA), which represents more than 100,000 members
worldwide. Bill is also an author and speaker and has written such books as ASP.NET
Professional Secrets, XML Web Services for ASP.NET, Web Services Enhancements, and the
Visual Basic .NET Bible (all from Wiley).

Example codes

ValidationForm_cs.aspx

VB Source

ValidationForm_vb.aspx
<%@ Page Language="VB" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sign In Form Validation Sample</title>
</head>
<body>
<div>
<h3>
<font face="Verdana">Sign In Form Validation
Sample</font></h3>
<form action="validationform_vb.aspx" method="post"
runat="server">
<hr width="600" size="1" noshade="noshade" />
<center>
<asp:ValidationSummary ID="valSum" runat="server"
HeaderText="You must enter a valid value in the following
fields:"
DisplayMode="SingleParagraph" Font-Names="verdana"
Font-Size="12" />
<br />
<br />
<!-- sign-in -->
<table border="0" width="600">
<tr>
<td colspan="3">
<table border="0" cellpadding="0" cellspacing="0"
width="100%">
<tr>
<td>
<font face="geneva,arial" size="-1"><b>Sign-
In Information</b></font>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Email Address:</font>
</td>
<td>
<asp:TextBox ID="email" Width="200px"
MaxLength="60" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="emailReqVal"
ControlToValidate="email" ErrorMessage="Email. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="emailRegexVal"
ControlToValidate="email" ErrorMessage="Email. "
Display="Static" ValidationExpression="^[\w-]
+@[\w-]+\.(com|net|org|edu|mil)$"
Font-Names="Arial" Font-Size="11" runat="server">
Not a valid e-mail address. Must follow
email@host.domain.
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Password:</font>
</td>
<td>
<asp:TextBox ID="passwd" TextMode="Password"
MaxLength="20" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="passwdReqVal"
ControlToValidate="passwd" ErrorMessage="Password. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="passwdRegexBal" ControlToValidate="passwd"
ErrorMessage="Password. "
ValidationExpression=".*[!@#$%^&*+;:].*"
Display="Static" Font-Names="Arial" Font-Size="11"
Width="100%" runat="server">
Password must include one of these (!@#$
%^&amp;*+;:)
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Re-enter
Password:</font>
</td>
<td>
<asp:TextBox ID="passwd2" TextMode="Password"
MaxLength="20" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="passwd2ReqVal"
ControlToValidate="passwd2" ErrorMessage="Re-enter Password. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1"
ControlToValidate="passwd2" ControlToCompare="passwd"
ErrorMessage="Re-enter Password. "
Display="Static" Font-Names="Arial" Font-Size="11"
runat="server">
Password fields don't match
</asp:CompareValidator>
</td>
</tr>
<tr>
<td colspan="3">
&nbsp;</td>
</tr>
<!-- personalization information -->
<tr>
<td colspan="3">
<table border="0" cellpadding="0" cellspacing="0"
width="100%">
<tr>
<td>
<font face="geneva,arial" size="-
1"><b>Personal Information</b></font>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">First Name:</font>
</td>
<td>
<asp:TextBox ID="fn" MaxLength="20" Width="200px"
runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Last Name:</font>
</td>
<td>
<asp:TextBox ID="ln" MaxLength="40" Width="200px"
runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Address:</font>
</td>
<td>
<asp:TextBox ID="address" Width="200px"
runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">State:</font>
</td>
<td>
<asp:TextBox ID="state" Width="30px" MaxLength="2"
runat="server" />&nbsp; <font
face="Arial" size="2">Zip Code:</font>&nbsp;
<asp:TextBox ID="zip" Width="60px" MaxLength="5"
runat="server" />
</td>
<td>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" ControlToValidate="zip"
ErrorMessage="Zip Code. "
ValidationExpression="^\d{5}$" Display="Static" Font-
Names="Arial"
Font-Size="11" runat="server">
Zip code must be 5 numeric digits
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Phone:</font>
</td>
<td>
<asp:TextBox ID="phone" MaxLength="20"
runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="phoneReqVal"
ControlToValidate="phone" ErrorMessage="Phone. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="phoneRegexVal"
ControlToValidate="phone" ErrorMessage="Phone. "
ValidationExpression="(^x\s*[0-9]{5}$)|(^(\([1-
9][0-9]{2}\)\s)?[1-9][0-9]{2}-[0-9]{4}(\sx\s*[0-9]{5})?$)"
Display="Static" Font-Names="Arial" Font-
Size="11" runat="server">
Must be in form: (XXX) XXX-XXXX
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td colspan="3">
&nbsp;</td>
</tr>
<!-- Credit Card Info -->
<tr>
<td colspan="3">
<font face="Arial" size="2"><b>Credit Card
Information</b></font>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Card Type:</font>
</td>
<td>
<asp:RadioButtonList ID="ccType" Font-
Names="Arial" RepeatLayout="Flow" runat="server">
<asp:ListItem>MasterCard</asp:ListItem>
<asp:ListItem>Visa</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="ccTypeReqVal"
ControlToValidate="ccType" ErrorMessage="Card Type. "
Display="Static" InitialValue="" Font-
Names="Verdana" Font-Size="12" runat="server">
*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Card Number:</font>
</td>
<td>
<asp:TextBox ID="ccNum" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="ccNumReqVal"
ControlToValidate="ccNum" ErrorMessage="Card Number. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:CustomValidator ID="ccNumCustVal"
ControlToValidate="ccNum" ErrorMessage="Card Number. "
ClientValidationFunction="ccClientValidate"
Display="Static" Font-Names="Arial"
Font-Size="11" runat="server">
Not a valid credit card number. Must contain 16
digits.
</asp:CustomValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Expiration Date:</font>
</td>
<td>
<asp:DropDownList ID="expDate" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem>06/00</asp:ListItem>
<asp:ListItem>07/00</asp:ListItem>
<asp:ListItem>08/00</asp:ListItem>
<asp:ListItem>09/00</asp:ListItem>
<asp:ListItem>10/00</asp:ListItem>
<asp:ListItem>11/00</asp:ListItem>
<asp:ListItem>01/01</asp:ListItem>
<asp:ListItem>02/01</asp:ListItem>
<asp:ListItem>03/01</asp:ListItem>
<asp:ListItem>04/01</asp:ListItem>
<asp:ListItem>05/01</asp:ListItem>
<asp:ListItem>06/01</asp:ListItem>
<asp:ListItem>07/01</asp:ListItem>
<asp:ListItem>08/01</asp:ListItem>
<asp:ListItem>09/01</asp:ListItem>
<asp:ListItem>10/01</asp:ListItem>
<asp:ListItem>11/01</asp:ListItem>
<asp:ListItem>12/01</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="expDateReqVal"
ControlToValidate="expDate" ErrorMessage="Expiration Date. "
Display="Static" InitialValue="" Font-
Names="Verdana" Font-Size="12" runat="server">
*
</asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br /><br />
<input runat="server" type="submit" value="Sign In"/>
<br /><br />
<hr width="600" size="1" noshade="noshade">

<script type="text/javascript">

function ccClientValidate(source, arguments)


{
var cc = arguments.Value;
var ccSansSpace;
var i, digits, total;

// SAMPLE ONLY. Not a real world actual credit card


algo.
// Based on ANSI X4.13, the LUHN formula (also known
as the modulus 10 -- or mod 10 -- algorithm )
// is used to generate and/or validate and verify
the accuracy of some credit-card numbers.

// Get the number, parse out any non digits, should


have 16 left
ccSansSpace = cc.replace(/\D/g, "");
if(ccSansSpace.length != 16) {
arguments.IsValid = false;
return; // invalid ccn
}

// Convert to array of digits


digits = new Array(16);
for(i=0; i<16; i++)
digits[i] = Number(ccSansSpace.charAt(i));

// Double & sum digits of every other number


for(i=0; i<16; i+=2) {
digits[i] *= 2;
if(digits[i] > 9) digits[i] -= 9;
}

// Sum the numbers


total = 0;
for(i=0; i<16; i++) total += digits[i];

// Results
if( total % 10 == 0 ) {
arguments.IsValid = true;
return; // valid ccn
}
else {
arguments.IsValid = false;
return; // invalid ccn
}
}

</script>
</center>
</form>
</div>
</body>
</html>

C#

<%@ Page Language="C#" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sign In Form Validation Sample</title>
</head>
<body>
<div>
<h3>
<font face="Verdana">Sign In Form Validation
Sample</font></h3>
<form action="validationform_cs.aspx" method="post"
runat="server">
<hr width="600" size="1" noshade>
<center>
<asp:ValidationSummary ID="valSum" runat="server"
HeaderText="You must enter a valid value in the following
fields:"
DisplayMode="SingleParagraph" Font-Names="verdana"
Font-Size="12" />
<br />
<br />
<!-- sign-in -->
<table border="0" width="600">
<tr>
<td colspan="3">
<table border="0" cellpadding="0" cellspacing="0"
width="100%">
<tr>
<td>
<font face="geneva,arial" size="-1"><b>Sign-
In Information</b></font>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Email Address:</font>
</td>
<td>
<asp:TextBox ID="email" Width="200px"
MaxLength="60" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="emailReqVal"
ControlToValidate="email" ErrorMessage="Email. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="emailRegexVal"
ControlToValidate="email" ErrorMessage="Email. "
Display="Static" ValidationExpression="^[\w-]
+@[\w-]+\.(com|net|org|edu|mil)$"
Font-Names="Arial" Font-Size="11" runat="server">
Not a valid e-mail address. Must follow
email@host.domain.
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Password:</font>
</td>
<td>
<asp:TextBox ID="passwd" TextMode="Password"
MaxLength="20" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="passwdReqVal"
ControlToValidate="passwd" ErrorMessage="Password. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="passwdRegexBal" ControlToValidate="passwd"
ErrorMessage="Password. "
ValidationExpression=".*[!@#$%^&*+;:].*"
Display="Static" Font-Names="Arial" Font-Size="11"
Width="100%" runat="server">
Password must include one of these (!@#$
%^&amp;*+;:)
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Re-enter
Password:</font>
</td>
<td>
<asp:TextBox ID="passwd2" TextMode="Password"
MaxLength="20" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="passwd2ReqVal"
ControlToValidate="passwd2" ErrorMessage="Re-enter Password. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1"
ControlToValidate="passwd2" ControlToCompare="passwd"
ErrorMessage="Re-enter Password. "
Display="Static" Font-Names="Arial" Font-Size="11"
runat="server">
Password fields don't match
</asp:CompareValidator>
</td>
</tr>
<tr>
<td colspan="3">
&nbsp;</td>
</tr>
<!-- personalization information -->
<tr>
<td colspan="3">
<table border="0" cellpadding="0" cellspacing="0"
width="100%">
<tr>
<td>
<font face="geneva,arial" size="-
1"><b>Personal Information</b></font>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">First Name:</font>
</td>
<td>
<asp:TextBox ID="fn" MaxLength="20" Width="200px"
runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Last Name:</font>
</td>
<td>
<asp:TextBox ID="ln" MaxLength="40" Width="200px"
runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Address:</font>
</td>
<td>
<asp:TextBox ID="address" Width="200px"
runat="server" />
</td>
<td>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">State:</font>
</td>
<td>
<asp:TextBox ID="state" Width="30px" MaxLength="2"
runat="server" />&nbsp; <font
face="Arial" size="2">Zip Code:</font>&nbsp;
<asp:TextBox ID="zip" Width="60px" MaxLength="5"
runat="server" />
</td>
<td>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" ControlToValidate="zip"
ErrorMessage="Zip Code. "
ValidationExpression="^\d{5}$" Display="Static" Font-
Names="Arial"
Font-Size="11" runat="server">
Zip code must be 5 numeric digits
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Phone:</font>
</td>
<td>
<asp:TextBox ID="phone" MaxLength="20"
runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="phoneReqVal"
ControlToValidate="phone" ErrorMessage="Phone. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="phoneRegexVal"
ControlToValidate="phone" ErrorMessage="Phone. "
ValidationExpression="(^x\s*[0-9]{5}$)|(^(\([1-
9][0-9]{2}\)\s)?[1-9][0-9]{2}-[0-9]{4}(\sx\s*[0-9]{5})?$)"
Display="Static" Font-Names="Arial" Font-
Size="11" runat="server">
Must be in form: (XXX) XXX-XXXX
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td colspan="3">
&nbsp;</td>
</tr>
<!-- Credit Card Info -->
<tr>
<td colspan="3">
<font face="Arial" size="2"><b>Credit Card
Information</b></font>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Card Type:</font>
</td>
<td>
<asp:RadioButtonList ID="ccType" Font-
Names="Arial" RepeatLayout="Flow" runat="server">
<asp:ListItem>MasterCard</asp:ListItem>
<asp:ListItem>Visa</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="ccTypeReqVal"
ControlToValidate="ccType" ErrorMessage="Card Type. "
Display="Static" InitialValue="" Font-
Names="Verdana" Font-Size="12" runat="server">
*
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Card Number:</font>
</td>
<td>
<asp:TextBox ID="ccNum" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="ccNumReqVal"
ControlToValidate="ccNum" ErrorMessage="Card Number. "
Display="Dynamic" Font-Names="Verdana" Font-
Size="12" runat="server">
*
</asp:RequiredFieldValidator>
<asp:CustomValidator ID="ccNumCustVal"
ControlToValidate="ccNum" ErrorMessage="Card Number. "
ClientValidationFunction="ccClientValidate"
Display="Static" Font-Names="Arial"
Font-Size="11" runat="server">
Not a valid credit card number. Must contain 16
digits.
</asp:CustomValidator>
</td>
</tr>
<tr>
<td align="right">
<font face="Arial" size="2">Expiration Date:</font>
</td>
<td>
<asp:DropDownList ID="expDate" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem>06/00</asp:ListItem>
<asp:ListItem>07/00</asp:ListItem>
<asp:ListItem>08/00</asp:ListItem>
<asp:ListItem>09/00</asp:ListItem>
<asp:ListItem>10/00</asp:ListItem>
<asp:ListItem>11/00</asp:ListItem>
<asp:ListItem>01/01</asp:ListItem>
<asp:ListItem>02/01</asp:ListItem>
<asp:ListItem>03/01</asp:ListItem>
<asp:ListItem>04/01</asp:ListItem>
<asp:ListItem>05/01</asp:ListItem>
<asp:ListItem>06/01</asp:ListItem>
<asp:ListItem>07/01</asp:ListItem>
<asp:ListItem>08/01</asp:ListItem>
<asp:ListItem>09/01</asp:ListItem>
<asp:ListItem>10/01</asp:ListItem>
<asp:ListItem>11/01</asp:ListItem>
<asp:ListItem>12/01</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="expDateReqVal"
ControlToValidate="expDate" ErrorMessage="Expiration Date. "
Display="Static" InitialValue="" Font-
Names="Verdana" Font-Size="12" runat="server">
*
</asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br />
<br />
<input runat="server" type="submit" value="Sign In" />
<br />
<br />
<hr width="600" size="1" noshade="noshade" />

<script type="text/javascript">

function ccClientValidate(source, arguments)


{
var cc = arguments.Value;
var ccSansSpace;
var i, digits, total;

// SAMPLE ONLY. Not a real world actual credit card


algo.
// Based on ANSI X4.13, the LUHN formula (also known
as the modulus 10 -- or mod 10 -- algorithm )
// is used to generate and/or validate and verify
the accuracy of some credit-card numbers.

// Get the number, parse out any non digits, should


have 16 left
ccSansSpace = cc.replace(/\D/g, "");
if(ccSansSpace.length != 16) {
arguments.IsValid = false;
return; // invalid ccn
}

// Convert to array of digits


digits = new Array(16);
for(i=0; i<16; i++)
digits[i] = Number(ccSansSpace.charAt(i));

// Double & sum digits of every other number


for(i=0; i<16; i+=2) {
digits[i] *= 2;
if(digits[i] > 9) digits[i] -= 9;
}

// Sum the numbers


total = 0;
for(i=0; i<16; i++) total += digits[i];

// Results
if( total % 10 == 0 ) {
arguments.IsValid = true;
return; // valid ccn
}
else {
arguments.IsValid = false;
return; // invalid ccn
}
}

</script>

</center>
</form>
</div>
</body>
</html>

You might also like