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. Only server-side form validation is used in this example.

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>")
      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" OnTextChanged="btnSubmit_Click" />

  <%-- 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" />

[Return to the Article]