Validating ASP.NET Server Controls


Introduction

Validation server controls are a series of controls that helps 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.

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.

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.

Using the RequiredFieldValidator control

<%@ 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" ID="Form1">
<
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.

Figure : Causing the RequiredFieldValidator server control to fire

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.

Using the CompareValidator server control

<%@ 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" ID="Form1">
<
p>
Password<br>
<
asp:TextBox id="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
&nbsp;<asp:CompareValidator id="CompareValidator1" runat="server" rrorMessage="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" ext="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). If they are equal, your page submits as valid.

Figure : In this example, the user mistyped the password and got an error message.

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.

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.

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>

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.

Figure : 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.

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 shows the error message that results if a user enters an incorrect e-mail address in the text box.

Figure : Validating whether an e-mail address is entered in a text box

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.
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.

Creating your own client-side validation functions

<%@ 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" ID="Form1">
<
p>Number: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
&nbsp;
<asp:CustomValidator id="CustomValidator1" runat="server" ontrolToValidate="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.

Figure : 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. Here the code determines whether the number entered in the text box on the ASP.NET page is even.

Creating your own server-side validation functions

<%@ 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" ID="Form1"><p>
Number:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>&nbsp;
<asp:CustomValidator id="CustomValidator1" runat="server" ontrolToValidate="TextBox1" ErrorMessage="Number must be even" OnServerValidate="ValidateNumber"></asp:CustomValidator></p>
<
p><asp:Button id="Button1" onclick="Button1_Click" runat="server" ext="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.

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. 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.

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 appear on the screen.

Figure : 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 . 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.

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.

Figure : 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.

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="Requiredfieldvalidator2" 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.

Figure : 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.


Similar Articles