Using the ASP.NET CustomValidator Control

The CustomValidator control enables you to validate a form field by using a custom method. For example, you can use the CustomValidator to perform validation which depends on database data. The CustomValidator control supports both server-side and client-side validation.

The CustomValidator control supports the following properties.

ControlToValidate – The id of the form field being validated.

Text – The error message displayed when there is a validation error.

The CustomValidator control also raises the following event.

ServerValidate – This event is raised on the server when the control performs validation.

Performing Server-Side Custom Validation

You associate a custom validation method with the CustomValidator control by providing an event handler for the ServerValidate event. For example, the following page contains a multiline TextBox control which enables a user to enter comments on a Web site. If the user enters text that does not include the word “good” then validation fails and an error message is displayed.

In Listing 1, the event handler for the ServerValidate event is named valComments_ServerValidate. Notice that the second parameter passed to this method is an instance of the ServerValidateEventArgs class. This class includes the following two properties:

Value – The value of the form field being validated.

IsValid – When this property is assigned the value True, the validation test is passed. When this property is assigned the value False, the validation test is not passed and the error message is displayed.

Performing Client-Side Validation

You can (optionally) perform client-side validation with the CustomValidator control. If you want to validate a form field on the client-side, then you need to write a custom JavaScript or VBScript method which is executed on the client. You must assign the name of your custom function to the CustomValidator control’s ClientValidationFunction property.

For example, the following page validates a user’s comments on both the server-side and client-side.

Notice that the client-side validation function looks very similar to the server-side function. Both functions take the same two parameters.