Home   Cover Cover Cover Cover
 

Validators


From Section 6.5.6 of the book

This example demonstrates various kinds of validators for web controls. It shows both the validation at the client and at the server.

Validators.aspx
<%@ Page Language="C#" %>
<html>

  <script Runat="server">
    void HandleClick(object sender, EventArgs e) {
      if (IsValid) label.Text = "ok"; else label.Text = "error!";
    }
  </script>

  <script Language="JavaScript">
    function ValidateEmail(source, arg) {
      if (arg.Value.indexOf("@") < 0)
        arg.IsValid = false;
      else
        arg.IsValid = true;
    }
  </script>

<body>
  <form Runat="server">

    Name:
    <asp:TextBox ID="name" Runat="server" />
    <asp:RequiredFieldValidator ID="nameVal" ControlToValidate="name" Text="*"
      ErrorMessage="Please enter a name" Runat="server" />
    <br>

    Age:
    <asp:TextBox ID="age" Runat="server" />
    <asp:RangeValidator ID="ageVal" ControlToValidate="age" Text="*"
      MinimumValue="0" MaximumValue="100" Type="Integer"
      ErrorMessage="Age must be between 0 and 120" Runat="server" />
    <br>

    Years of membership:
    <asp:TextBox ID="memberSince" Runat="server" />
    <asp:CompareValidator ID="memberVal" Text="*"
      ControlToValidate="memberSince" Operator="LessThan"
      ControlToCompare="age" Type="Integer"
      ErrorMessage="Age is less than years of membership" Runat="server" />
    <br>

    E-Mail:
    <asp:TextBox ID="email" Runat="server" />
    <asp:CustomValidator ID="emailVal" ControlToValidate="email" Text="*"
      ClientValidationFunction="ValidateEmail"
      ErrorMessage="Invalid E-mail address" Runat="server" />
    <br>

    <asp:Button ID="ok" Text="Send" OnClick="HandleClick" Runat="server" />
    <br>

    <asp:Label ID="label" Runat="server" /><br>
    <asp:ValidationSummary Runat="server" />
  </form>
</body>
</html>

Try it

   http://dotnet.jku.at/book/samples/6/Validators.aspx