O'Reilly logo

Programming ASP .NET by Dan Hurwitz, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 simply 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 both 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, while the client-side method must be written in a scripting language understood by the browser, such as VBScript or JavaScript.

You’ll create a simple form that will request an even number from the user, and report the error if the number is not evenly divisible by 2. You can imagine, however, that you could perform a checksum on a credit card or ISBN or otherwise perform complex data checking.

The heart of this example is the CustomValidator control:

<asp:CustomValidator 
id="cvEven"
controlToValidate="txtEven"
Display="Static"
runat="server"
ClientValidationFunction="ClientValidator"
OnServerValidate="ServerValidator">
Well, that's odd...
</asp:CustomValidator>

The CustomValidator takes many of the usual attributes, such as an ID, runat, ControlToValidate, and Display. In addition, this validator has an attribute ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required