Custom Validation

There are times when the validation of your data is so specific to your application that you will need to write your own validation method. The CustomValidator is designed to provide all the infrastructure support you need. You point to your validation method and have it return a Boolean value: true or false. The CustomValidator control takes care of all the rest of the work.

Because validation can be done on the client or on the server, depending on the browser, the CustomValidator has attributes for specifying a server-side and a client-side method for validation. The server-side method can be written in any .NET language, such as C# or VB.NET, but the client-side method must be written in a scripting language understood by the browser, such as VBScript or JavaScript.

Once again, create a new web site, named CustomValidator, and copy the RegularExpressionValidator web site to get you started. In this example, you want to ensure that the user enters an even number.

This time, you’ll report an error if the number is not evenly divisible by 2. You can imagine, however, that you could use this technique perform a checksum on a credit card or ISBN or otherwise perform complex data checking.

Tip

Most of these checks can be done more easily with a Regular Expression Validator; the custom validator should be used only as a last resort.

Replace the RegularExpressionValidator with a CustomValidator. Set the ControlTo-Validate field, and set EnableClientScript to true (the default). ...

Get Programming ASP.NET, 3rd Edition 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.