Developer

ASP.NET controls make client-side validation a snap

Writing form validation code is a repetitive, boring business. See how ASP.NET's new validation controls make it easy to ensure your apps get the right data.


As programmers, we all know that users are funny creatures, just as likely to enter their password into the user ID field as they are to do things the other way around. So you’ve probably found that a lot of your programming time is spent validating or cleaning up the input your application receives from its users. In a Windows app, this code is comparatively easy to write, but in a Web application, you’ll often have to resort to writing messy, repetitive client-side scripts to accomplish this task. And then, you’ll still have to figure out the best way to communicate with the users that they messed up.

Luckily, ASP.NET includes some nifty automatic validation controls you can use to guarantee that your application receives the input it expects. Best of all, these controls work declaratively: Simply place them on a Web form, set a few properties, and you’re ready to go.

Requiring input with the RequiredFieldValidator
We'll begin with a simple example to illustrate how ASP.NET’s data validation controls work. Ensuring that the user doesn’t leave a particular input field blank is a common enough task to start with. Let's assume that we’re talking about the user’s name. You’d likely have a TextBox control on the form, perhaps called txtName, and you’d use the RequiredFieldValidator control, which simply checks that the form field to which it’s assigned has a value. The validation is triggered when any control (usually a button) whose CausesValidation control is set to true fires a predefined event (a click in the case of a button) or when your code invokes it.

You assign a validator to a particular control using its ControlToValidate property, and you can specify an error message for the control to display if a validation error occurs using the ErrorMessage property. Since the default error message is the name of the control, it’s usually a good idea to set something more helpful here, like “Your name is required.”

Finally, assume that you also have a Submit button on the form in question, and its CausesValidation property is set to true (the default for buttons). If a user were to click Submit without entering a name, Figure A would be the result.

Figure A
Easy form validation


By peeking at the generated source for the page, it’s easy to see how this works. As you can see from Listing A, by default, ASP.NET includes a client-side script with the HTML for the form. This script is invoked when the form is submitted and makes the browser perform any validation on your behalf. This is handy stuff. You don't have to write the validation code for your form, and all the validation is done on the client side. Users will find out immediately if their submission did not validate correctly, and they can still see any data they entered into the form.

You can change a validation control’s behavior from the default client-side validation to server-side validation by setting the control’s EnableClientScript property to false. You’ll want to do so if you know that your client browsers don’t support the necessary scripting capabilities, if you simply don’t want the extra overhead of sending embedded script in the page, or if your validation involves external dependencies that make client-side validation impossible (a database lookup, perhaps).

Meet the other ASP.NET validation controls
In addition to the RequiredFieldValidator, the Web Forms library contains a few other validation controls that are intended to perform different kinds of validation:
  • ·        CompareValidator validates the contents of one control against the contents of another or against a constant. Validation fails if both controls’ contents don’t match exactly.
  • ·        RangeValidator validates a control against a range of values. Validation fails if the control’s value doesn’t fall within the defined range.
  • ·        RegularExpressionValidator validates a control using a regular expression, which you can either write yourself or choose from a predefined list. Validation fails if the control’s value doesn’t fit the expression.
  • ·        CustomValidator validates a control using a custom script or function you provide. To perform client-side validation, you’ll add the validation script directly to the HTML for the ASP.NET page.

In addition to these, there is the ValidationSummary control, which echoes any validation error messages produced on a form. ValidationSummary is useful on long forms, as it keeps users from having to scroll around and see what they did wrong.

Validation in action
To get a better idea of the usefulness of each of these validation controls, let’s run through a detailed example. In Listing B, you’ll find the codebehind file for a Web form that makes use of validation controls. As you can see from Figure B, this particular form collects the name, password, favorite color, phone number, and birth month of the user.

Figure B
The fleshed-out user information form


The Name and Favorite Color fields are both validated with RequiredFieldValidator control. You’ve already seen how it can be used to validate the contents of a TextBox, but what about a DropDownList control? RequiredFieldValidator works by comparing the value of the control it is validating against the value it holds internally in its InitialValue property, which is an empty string (“”) by default. So as long as a DropDownList’s initially selected item has a value that’s equal to the InitialValue property of its associated RequiredFieldValidator, everything will work as expected. You can see this in action in the code snippet below:
ColorValidator.ControlToValidate = cboColor.ID;
ColorValidator.ErrorMessage = "Please pick a color";
ColorValidator.InitialValue =
cboColor.SelectedItem.Value;
 

The two Password fields require users to double-enter their password. I use a CompareValidator, PasswordValidator, to compare the two fields and ensure that the user entered the same password in both boxes:
PasswordValidator.ControlToValidate = txtConfirm.ID;
PasswordValidator.ControlToCompare = txtPassword.ID;
PasswordValidator.ErrorMessage =
"Passwords do not match";
 

RangeValidator controls can validate data in a variety of formats, which is controlled by passing a member of the ValidationDataType enum to the Type property. Below, you can see where I set the RangeValidator control MonthValidator to ensure that the Birth Month field contains an integer value between 1 and 12:
MonthValidator.ControlToValidate = txtMonth.ID;
MonthValidator.Type =
ValidationDataType.Integer;
MonthValidator.MinimumValue = “1”;
MonthValidator.MaximumValue = “12”;
MonthValidator.ErrorMessage =
"Please enter a valid month";
 

Finally, I use a RegularExpressionValidator control, PhoneNumberValidator, to validate the phone number field. RegularExpressionValidators can be extremely useful. The only trick to their use is creating the regular expression in the first place. Luckily, Visual Studio .NET includes a set of predefined expressions you can choose from if you build your ASP.NET pages using its designer. Here, you can see the configuration code for PhoneNumberValidator. Notice that the validation expression must be properly escaped because of all the backslashes:
PhoneNumberValidator.ErrorMessage =
"Enter a valid phone number or leave blank.";
PhoneNumberValidator.ControlToValidate = txtPhone.ID;
PhoneNumberValidator.ValidationExpression =
"((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}";

The sample Web form also uses a ValidationSummary control, placed directly under the Submit button, to display any validation error messages to the user. Figure C shows what happens if a user simply presses the Submit button without entering anything into the form. Notice how the ValidationSummary echoes each individual validation error message.

Figure C
Hey, shouldn’t a password be required?


Looking closely at Figure C, you might notice something strange. The Password, Phone Number, and Birth Month fields seem to validate fine if the user simply leaves them blank. However, if the user types in something incorrect, like the word “May” in the Birth Month field, the validation fails as expected. This fact brings up an important point about ASP.NET’s validation controls: Each control will validate based on only one particular criterion. Any field not validated by a RequiredFieldValidator is effectively optional.

Custom validation example
As useful as they are, sometimes the validation rules you need to apply are simply too complicated to handle using the stock validation controls. In those situations, the CustomValidator control becomes useful.

When using client-side validation, you’ll need to include the validation script in the HTML for the Web form. The script function should not return a value (a Sub in VBScript) and should accept two parameters: source and arguments. The second parameter, arguments, is the important one. You can access the value of the control to validate from the arguments.Value property, and you indicate the success or failure of validation through the arguments.IsValid property.

Returning to the example I used before, suppose we wanted to limit the use of our Web form to only those users with a birthday in January, June, or December—not something easily done with the stock validation controls. Using a CustomValidator and a custom client-side validation script, it’s a snap. The following code configures the CustomValidator control RightMonthsValidator to call a client-side script named CheckMonths to perform validation on the Birth Month field:
RightMonthsValidator.ErrorMessage =
"You were born in the wrong month";
RightMonthsValidator.ControlToValidate = txtMonth.ID;
RightMonthsValidator.ClientValidationFunction =
"CheckMonths";
 

Here’s the very simple client-side CheckMonths script:
function CheckMonths(source, arguments)
{
if ((arguments.Value == 1) ||
(arguments.Value == 6) ||
(arguments.Value == 12))
arguments.IsValid=true;
else
arguments.IsValid=false;
}
 

Figure D shows what happens when a user enters 8 in the Birth Month field.

Figure D
Talk about an exclusive club…


As you can see, ASP.NET’s validation controls make validating user data a much less arduous chore. Since all these controls do their validation on the client side by default, you’ll find your validated forms will be much more pleasing for your users to use, as well as for you to create.

 

 

Editor's Picks