When you think ASP, think...
Recent Articles xml
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips
spgif spgif

Book Reviews
Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
Web Hosts
Author an Article
spgif spgif

ASP ASP.NET ASP FAQs Feedback topnav-right
Print this Page!
Published: Wednesday, July 31, 2002

Using the CustomValidator Control

By Scott Mitchell


One annoying task that most every developer has had to face in the past is form validation. Since forms are an integral part of dynamic, data-driven Web sites, it is essential that a user's query into a form fit the specified guidelines. For example, in a Web site like Amazon.com where users are entering shipping and billing information, it is vital that the user enter credit card numbers, zip codes, email addresses, and other information in an acceptable format.

- continued -

With classic ASP, performing form field validation was annoying, at best. Developers had to write their own validation routines and cut and paste them in the various ASP scripts that needed to employ form validation techniques. All in all, it was a real headache. Fortunately ASP.NET fixes all of this by its use of validation Web controls.

Validation Web controls are ASP.NET Web controls designed specifically to validate form field entries. For example, ASP.NET contains a RequiredFieldValidation control, which, as its name suggests, can be used to ensure that the user enters a value into a form field (such as a TextBox). Specifically, ASP.NET provides the following form field validation controls:

  1. RequiredFieldValidator - Checks to make sure the user entered a value.
  2. CompareValidator - Compares a form field's value with the value of another form field using relations like less than, equal, not equal, etc.
  3. RangeValidator - Ensures that a form field's value is within a certain range.
  4. RegularExpressionValidator - Makes sure that a form field's value corresponds to a specified regular expression pattern.
  5. CustomValidator - Checks the form field's value against custom validation logic that you, the developer, provide.

This article does not aim to discuss the specifics of all of these validation Web controls. Rather, it will dissect a particular control, the CustomValidator validation control. (For more information on the other validation Web controls be sure to read Server Control Form Validation.)

An Overview of the CustomValidator Web Control

By simply using the first four ASP.NET validation Web controls (the RequiredFieldValidator, the CompareValidator, the RangeValidator, and the RegularExpressionValidator), you will be able to solve the vast majority of your form validation needs. However, there may be times when you need to perform more complex validation logic. For example, imagine that you had a questionnaire that asked the user a number of questions in radiobutton and checkbox form. Imagine that you had a series of checkboxes that corresponded to the hobbies sports, reading, and swimming, and you asked the ready to check all hobbies that he enjoyed. Below that, imagine that you had text that read, "If you have both sports and swimming as a hobby, please specify when you learned to swim," and beneath that you had a list of radio buttons listing various age groups. The validation for those radio buttons would hinge on the values chosen by the user in the checkbox list, no? In such a scenario, you would need to use the CustomValidator to provide the validation logic.

Recall that each of ASP.NET's validation Web controls contain a required property called ControlToValidate. This property specifies what form field the validation control is set to validate. Hence, our custom validation function has the simple task before it:

  1. Read in the value of the form field that the CustomValidator is set to validate,
  2. Perform the validation logic, and
  3. Specify if the form field is valid or not.

With the built-in validation controls, these steps are all performed behind the scenes for us, free of charge. However, when we're using a CustomValidator, we must do this work ourselves. To do this, we must write a server-side validation event handler that will be responsible for performing the three steps above for our CustomValidator control. This server-side validation event handler must have the following definition:

Sub FunctionName(sender as Object, args as ServerValidateEventArgs)
End Sub

Take note of the args parameter, which is the second parameter (of type ServerValidateEventArgs) in our CustomValidator's server-side validation event handler. This parameter contains two properties that are vitally important:

  1. Value - indicates the value of the form field the CustomValidator control is validating.
  2. IsValid - a Boolean property that you must set to reflect if the form field's entry is valid or not. Set IsValid to true if the Value is valid, false otherwise.

Finally, when using the CustomValidator, we have to supply not only the ControlToValidate property, but also the OnServerValidate event has to be wired up to our server-side validation event handler.

Building a Simple CustomValidator Control

Imagine that you run a Web site for math nerds and that you have a form for users to provide some personal information to improve your knowledge of your site's demographics. Being math nerds, you may wish to ask them what their favorite prime number is. As you'll recall from many years ago, a prime number is a number that is only divisible by the number 1 and itself. Numbers like 13, 23, and 37 are prime, for example. You'd like to use the ASP.NET validation control model to provide validation on the user's entry to ensure that it's prime. Unfortunately there is no PrimeNumberValidation Web control, so we'll have to use a CustomValidator.

The below code shows a simple Web form with a TextBox and a Button, and a CustomValidator validating that the number entered into the TextBox is indeed prime. (There's also two CompareValidator controls to ensure that the user enters a positive integer into the TextBox.)

<script language="vb" runat="server">
  Sub btnSubmit_Click(sender as Object, e as EventArgs)
    If Page.IsValid then
      Response.Write("<font color=""red""><i>" & txtPrimeNumber.Text & _
                     " is, indeed, a good prime number.</i></font>")
      Response.Write("<font color=""red""><i>" & txtPrimeNumber.Text & _
                     " is <b>not</b> a prime number.</i></font>")
    End If
  End Sub

  Sub PrimeNumberCheck(sender as Object, args as ServerValidateEventArgs)
    Dim iPrime as Integer = Cint(args.Value), iLoop as Integer, _
        iSqrt as Integer = CInt(Math.Sqrt(iPrime))

    For iLoop = 2 to iSqrt
      If iPrime mod iLoop = 0 then
        args.IsValid = False
        Exit Sub
      End If

    args.IsValid = True
  End Sub

<form method="post" runat="server">
  Enter your favorite prime number:
  <asp:textbox id="txtPrimeNumber" runat="server" />

  <%-- Create the CustomValidator control --%>
  <asp:CustomValidator runat="server" id="custPrimeCheck"
        ErrorMessage="Invalid Prime Number" />

  <%-- Create two CompareValidator controls: the first ensures that 
      the number entered by the user is an Integer; the second 
      makes sure it is positive. --%>
  <asp:CompareValidator runat="server" id="compPrimeNumber"
        Operator="DataTypeCheck" Type="Integer"
        Display="Dynamic" ControlToValidate="txtPrimeNumber"
        ErrorMessage = "You must enter an integer value." />
  <asp:CompareValidator runat="server" id="compPrimeNumberPositive"
        Operator="GreaterThan" Type="Integer"
        Display="Dynamic" ValueToCompare="0"
        ErrorMessage = "You must enter a value greater than zero." />

  <p><asp:button id="btnSubmit" runat="server"
          OnClick="btnSubmit_Click" Text="Submit" />
[View a Live Demo!]

If you're a bit rusty on the math, the validation logic in the PrimeNumberCheck event handler may be a bit confusing. First, note that we are reading the value that the user entered into the txtPrimeNumber TextBox by accessing args.Value, storing it in a variable iPrime. Next, we compute the square root of the number entered by the user. We then loop from 2 to the square root of the user's entry, checking to see if any numbers within that range evenly divide the number the user entered. (iPrime mod iLoop computes the remainder of iPrime divided by iLoop - if this remainder equals 0 then iLoop evenly divides iPrime.) If any numbers evenly divide iPrime then obviously iPrime is not prime. If this is the case we set args.IsValid to False and exit the event handler. If we exit the loop, that means that the number is prime, so we set args.IsValid to True. (For those whose math skills aren't rusty, you may wish to take a moment to prove that you only need to loop from 2 to the square root of iPrime as opposed from 2 to iPrime...)

Providing Client-Side Validation

One of the nice things about the built-in ASP.NET validation controls is that they all provide client-side validation for uplevel browsers. For example, if you visit the live demo with an uplevel browser you'll note that the CompareValidators exhibit client-side validation (enter a value of "bob" into the TextBox and tab out of it to see what I mean), while the CustomValidator does not (try entering a nonprime number, such as 6, into the TextBox - you are not alerted to the fact that the number you entered is not prime until you submit the form).

Realize that there is no downside to providing client-side validation. Regardless of whether or not your CustomValidator provides client-side validation, the server-side validation will always occur. (This is true for all ASP.NET validation Web controls.) So, providing client-side validation only has the upside of making your custom validation more friendly for users whose browsers can support the DHTML and JavaScript requirements.

To provide client-side form validation for a CustomValidator you must first write a client-side function that takes two input parameters (for consistencies sake, call them sender and args. For the client-side function, you should strongly consider writing it using JavaScript, since JavaScript is universally recognized by browsers while VBScript is only recognized by Internet Explorer. So, for our prime number example, we'd simply replicate the server-side validation event handler as a client-side function in JavaScript, resulting in the following client-side code:

<script language="JavaScript">
  function CheckPrime(sender, args)
    var iPrime = parseInt(args.Value);
    var iSqrt = parseInt(Math.sqrt(iPrime));

    for (var iLoop=2; iLoop<=iSqrt; iLoop++)
      if (iPrime % iLoop == 0) 
         args.IsValid = false;

    args.IsValid = true;
// -->
[View a Live Demo!]

Note that the function's input parameters - sender and args - are untyped. That is, there is no explicit mention of what data type they are. This is due to the fact that JavaScript (and VBScript, for that matter) are type-free languages, meaning variables may assume any type. While the above code has changed syntactically from the server-side event handler example (written in VB.NET), the semantics have remained the same. We simply loop from 2 to the square root of the number the user entered, checking to see if the number is evenly divided by the looping variable. (Note that in JavaScript x % y is equivalent to VB.NET's x Mod y.)

To add the client-side validation, all that needs to be done is to include the above client-side SCRIPT block into the ASP.NET Web page and to set the CustomValidator's ClientValidationFunction property to the name of the client-side validation function, CheckPrime in this example. Be sure to view the live demo to see the client-side validation in action!


In this article we examined the CustomValidator control, ASP.NET's most flexible validation Web control. We looked at how to wire up a server-side validation event handler, as well as how to specify client-side validation. While ASP.NET's built-in validation controls may provide adequate for the majority of form validation needs, it's always nice to have a thorough understanding of the CustomValidator Web control for those times when the built-in controls just won't cut it.

Happy Programming!

  • By Scott Mitchell

  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article