CoverStory
LANGUAGES: VB.NET
ASP.NET
VERSIONS: 1.1 | 2.0
Input Validation
Using the Validation Controls in ASP.NET
By Wei-Meng Lee
One of the first lessons a developer learns is the concept
of Garbage In, Garbage Out (GIGO). If a user enters invalid data into your
application, they can expect the output to be garbage, as well. While this term
has been around for a long time, in today s applications you simply cannot
afford to have users enter garbage into your applications. As the developer, you
must stop them before your application starts to process it. This process is
known as input validation.
In this article, I ll show you how to use the validation
controls in ASP.NET, and, in particular, how the validation controls have been
improved in ASP.NET 2.0.
Basic Validation Controls
To see how the validation controls work, let s create a
new Web site project using Visual Studio 2005. Name the Web site
C:\ValidationControls.
In this section, you ll see how to use the following basic
validation controls:
- RequiredFieldValidator (for ensuring a specified
control has a value)
- CompareValidator (for comparing the values of
two controls)
- RegularExpressionValidator (for ensuring that a
control has a value matching a specified pattern)
- RangeValidator (for checking that the value of a
control is within a specified range)
In the Default.aspx page, first insert a 4 x 7 table
(Layout | Insert Table). Populate the form with the various controls (Label,
TextBox, RequiredFieldValidator, CompareValidator, RegularExpressionValidator,
and RangeValidator) and name them as shown in Figure 1. Next, set the
properties of the controls as listed in Figure 2. Default.aspx should look like
Figure 3.
Figure 1: Populating the
Default.aspx page with the various controls.
|
Control Name
|
Property
|
Value
|
|
TextBox1
|
TextMode
|
Password
|
|
TextBox2
|
TextMode
|
Password
|
|
Button1
|
Text
|
Submit
|
|
RequiredFieldValidator1
|
ControlToValidate
|
TextBox1
|
|
ErrorMessage
|
User ID required
|
|
RequiredFieldValidator2
|
ControlToValidate
|
TextBox2
|
|
ErrorMessage
|
Name required
|
|
RequiredFieldValidator3
|
ControlToValidate
|
TextBox3
|
|
ErrorMessage
|
Password required
|
|
RequiredFieldValidator4
|
ControlToValidate
|
TextBox5
|
|
ErrorMessage
|
E-mail required
|
|
RequiredFieldValidator5
|
ControlToValidate
|
TextBox6
|
|
ErrorMessage
|
Please enter your age
|
|
CompareValidator1
|
ControlToCompare
|
TextBox3
|
|
ControlToValidate
|
TextBox4
|
|
Operator
|
Equal
|
|
ErrorMessage
|
Passwords do not match
|
|
RegularExpressionValidator1
|
ControlToValidate
|
TextBox5
|
|
ErrorMessage
|
Incorrect email address
|
|
ValidationExpression
|
\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
|
|
RangeValidator1
|
ControlToValidate
|
TextBox6
|
|
ErrorMessage
|
Invalid age range
|
|
MaximumValue
|
60
|
|
MinimumValue
|
18
|
Figure 2: The
values of the various control properties.
Figure 3: Default.aspx after setting
the various control properties.
To see how the various validation controls work, press F5
to debug the Web application. Try clicking the Submit button without filling in
the TextBox controls. You ll see the error messages displayed next to each
TextBox control. Also, when you enter the password in both TextBox controls,
they must be identical or else an error message is displayed. E-mail entered
must also be in the valid format. Lastly, the age entered must be within 18 to
60. Figure 4 shows some of the error messages displayed.
Figure 4: Testing the application.
If you examine each of the validation controls, you ll
find that, by default, the EnableClientScript property is set to True. This
indicates that the validation control should perform its validation on the
client side if the Web browser supports it. The beauty of the validation
controls is that ASP.NET will automatically generate the client-side JavaScript
to perform the validation; there is no need for you to write JavaScript code.
Setting the EnableClientScript property to True helps
validate the data on the client side, and helps ensure that all the data posted
to the server is always valid. However, this is not always the case. If the Web
browser does not support client scripting (or, most likely, the user has
disabled client scripting), then un-validated data will still be posted back to
the server side. In this case, you must validate the data before proceeding
further. This can be done by calling the Validate method of the Page class on
the server, then checking the IsValid property. Extending the example above,
double-click the Submit button and code the event handler as shown in Figure 5.
Protected Sub Button1_Click( _
ByVal sender As Object,
_
ByVal e As
System.EventArgs) _
Handles Button1.Click
Page.Validate()
If Page.IsValid Then
'---continue with the
processing---
Else
'---print the error
message for each control---
Dim errorMessage As
String = String.Empty
For Each validator As
IValidator In Page.Validators
If Not
validator.IsValid Then
errorMessage +=
"<br>" & validator.ErrorMessage
End If
Next
Response.Write(errorMessage)
End If
End Sub
Figure 5: Extending
the validation example.
In the block of code shown in Figure 5, I first call the
Validate method to force all the validation controls to perform their
validation. Then, I check to see if the data submitted is valid. If any one of
the validation controls fails, I ll loop through all the validation controls on
the page and print their respective error message.
ValidationSummary Control
In addition to the basic validation controls demonstrated
in the last section, there is also a control known as the ValidationSummary
control. The ValidationSummary control presents a summary of all the validation
errors that have occurred on a form. Perform the following steps to see how the
ValidationSummary control works.
Add a ValidationSummary control to the form (see Figure 6).
Set the Text property of each validation control to * . The Web form should
now look like that shown in Figure 7. Press F5 to test the application. Leave
all the fields empty and click the Submit button. You should see the output as
shown in Figure 8.
Figure 6: Using the
ValidationSummary control.
Figure 7: Setting the Text property
of each validation control.
Figure 8: The ValidationSummary
control in action.
As you can (hopefully) deduce:
- If the Text property of the validation control
is empty, the text in the ErrorMessage property will be used as the error
message for the validation control.
- If the Text property of the validation control
is set, the text will then be used as the error message of the validation
control. The text set in the ErrorMessage property will be used by the ValidationSummary
control.
One interesting feature of the ValidationSummary control
is its ability to display a message box on the client side (Web browser). To do
so, set its ShowMessageBox property to True. You can also turn off the display
of the error message on the page itself by setting the ShowSummary property to
False. Figure 9 shows the ValidationSummary control displaying a message box on
the client side.
Figure 9: Displaying an error
message on the client side.
Validation Group
In ASP.NET 1.x, all controls in a single page are
validated together. For example, suppose you have a Search button and a Get
Title button, as shown in Figure 10. If you use a RequiredFieldValidator
validation control on the ISBN textbox, then clicking the Search button will not
result in a postback if the ISBN textbox is empty. This is because the entire
page is invalidated as long as one control fails the validation.
Figure 10: Multiple forms on a page.
In ASP.NET 2.0, group validation allows controls in a page
to be grouped logically so that a postback in one group is not dependent on
another. The best way to explore this new feature is to create a form with
multiple postback controls, add a validator control to one of them, then assign
each control to a separate group.
Using Visual Studio 2005, create a new Web site project
and name the project C:\ValidationGroup. Populate the default Web Form with the
Panel, TextBox, and Button controls shown in Figure 11.
Figure 11: A page with multiple
controls.
In the top panel (Panel control 1), you ll configure the
Search button to post the search string to the server, which in turn will
redirect to Google s site. To do so, double-click on the Search button
(btnSearch) and enter the following code in the code-behind to redirect the
search string to Google s site:
Sub btnSearch_Click(ByVal sender As Object, _
ByVal e
As System.EventArgs) _
Handles
btnSearch.Click
Dim queryStr As String =
_
HttpUtility.UrlEncode(txtSearch.Text)
Response.Redirect("http://www.google.com/search?q="
_
& queryStr)
End Sub
The TextBox control contained in the bottom panel (Panel
control 2) will take in an ISBN and perhaps perform some processing (such as retrieve
details of a book from Amazon.com). Next, associate the RequiredFieldValidator
control with the ISBN textbox (you can configure it in Source View):
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
Runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="txtISBN"
SetFocusOnError="True">
ISBN required</asp:RequiredFieldValidator>
To divide the controls into two separate validation
groups, switch to Source View and use the ValidationGroup attribute, as highlighted
in bold in the code sample shown in Figure 12.
...
<asp:TextBox ID="txtSearch" Runat="server"
Width="320px"
Height="22px">
</asp:TextBox>
<asp:Button ID="btnSearch" Runat="server"
Text="Search" ValidationGroup="SearchGroup"
/>
...
<asp:TextBox ID="txtISBN" Runat="server"
Width="212px"
Height="22px">
</asp:TextBox>
<asp:Button ID="btnGetTitle"
Runat="server"
Text="Get
Title"
ValidationGroup="BooksGroup" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
Runat="server" ErrorMessage="RequiredFieldValidator"
ControlToValidate="txtISBN"
ValidationGroup="BooksGroup">ISBN required
</asp:RequiredFieldValidator>
...
Figure 12: Use the
ValidationGroup attribute to divide the controls into two separate validation
groups.
The Search button is assigned the SearchGroup validation group
while the Get Title button and the RequiredFieldValidator are assigned to the
BooksGroup validation group. Press F5 to test the application. Now you can
click the Search and Get Title buttons independently of each other. Note that controls
that don t set the ValidationGroup attribute belong to the default group, thus
maintaining backward compatibility with ASP.NET 1.x.
Conclusion
You ve seen how the validation controls in ASP.NET 1.1 and
2.0 work. You ve also seen how the validation controls can be made to work on
the server side if client-side scripting has been disabled. In any case, proper
validation of user input data is crucial to ensuring the security and proper
working of your Web application. If you ve not taken the task of user input
validation seriously, now is the time to do so.
The sample code
accompanying this article is available for download.
Wei-Meng Lee (http://weimenglee.blogspot.com)
is a technologist and founder of Developer Learning Solutions, a technology
company specializing in hands-on training on the latest Microsoft technologies.
Wei-Meng speaks regularly at international conferences and has authored and co-authored
numerous books on .NET, XML, and wireless technologies, including ASP.NET 2.0: A Developer s Notebook and Visual Basic 2005 Jumpstart (both from O Reilly
Media, Inc.). Wei-Meng also is a Microsoft MVP.