CustomValidator Demo

In this demo we'll illustrate how to use a CustomValidator validation control to determine if a user's input is a prime number or not. Both server-side and client-side form validation is used in this example. Try entering a nonprime number (such as 6) and then tab out of the TextBox. If you are using an uplevel browser you will note that the Error Message appears automatically - that is, you don't have to first submit the form in order for it to display the error message!


Enter your favorite prime number:


Source Code
<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>")
    Else
      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
    Next

    args.IsValid = True
  End Sub
</script>

  <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;
           return;
        }

      args.IsValid = true;
    }
  // -->
  </script>

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

  <%-- Create the CustomValidator control --%>
  <asp:CustomValidator runat="server" id="custPrimeCheck"
        ControlToValidate="txtPrimeNumber"
        OnServerValidate="PrimeNumberCheck"
        ClientValidationFunction="CheckPrime"
        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"
        ControlToValidate="txtPrimeNumber"
        ErrorMessage = "You must enter a value greater than zero." />

  <p><asp:button id="btnSubmit" runat="server"
          OnClick="btnSubmit_Click" Text="Submit" />
</form>


[Return to the Article]