Chapter 17A. Custom Validators in Web Forms

In Lesson 16A I showed you how to use all of the standard validation controls. Sometimes, you will find that none of the standard validation controls perform the exact type of validation that you need. In this lesson I show you how to create and use a CustomValidator control.

The CustomValidator control uses all of the same properties as the standard validation controls, plus two very unique properties. These are the unique properties of the CustomValidator:

  • ClientValidationFunction — This is the name of the client-side script used to perform validation on the client. This property is not required.

  • ValidateEmptyText — This Boolean property is used to trigger validation when the value of input field specified by the ControlToValidate property is empty. The default value is false.

Another unique feature of the CustomValidator is that the ControlToValidate property is not required. If the ControlToValidate property is left blank, the CustomValidator is always triggered on postback, unless it belongs to a different ValidationGroup from the control that triggered the postback.

The CustomValidator has one unique event:

  • ServerValidate — This event is raised when the custom validation is performed on the server. This is required.

This is the markup for a CustomValidator:

<asp:CustomValidator ID="CustomValidator1" runat="server"
    ErrorMessage="CustomValidator"
    OnServerValidate="CustomValidator1_ServerValidate" />

Notice that the OnServerValidate method points ...

Get ASP.NET 4 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.