Windows Systems Programming: Spring 2004

[ Home | Syllabus | Course Notes | Assignments | Search]


Validation Controls

All but last derive from common base class—BaseValidator and share

//// Example
<asp:TextBox ID="Password" TextMode="Password" RunAt="server" />

<asp:RequiredFieldValidator
  ControlToValidate="Password"
  ErrorMessage="Required field"
  Display="static" 
  ForeColor="blue"
  RunAt="server"
/>
//// adding check for at least 8 characters
<asp:RegularExpressionValidator
   ControlToValidate="Password"
   ValidationExpression=".{8,}" 
   ErrorMessage="You must enter at least 8 characters"
   Display="dynamic"
   ForeColor="blue"
   RunAt="server" />

RangeValidator

<asp:TextBox ID="Percent" RunAt="server" />

<asp:RangeValidator
  ControlToValidate="Percent"
  MinimumValue="0"
  MaximumValue="100"
  Type="Integer"
  ErrorMessage="Value out of range"
  Display="static"
  RunAt="server"
/>
//// example using Dates
<asp:TextBox ID="MyDate" RunAt="server" />

<asp:RangeValidator
  ControlToValidate="MyDate"
  MinimumValue="10/01/2002"
  MaximumValue="12/31/2002"
  Type="Date"
  ErrorMessage="Date out of range"
  Display="static"
  RunAt="server"
/>

CompareValidator

<asp:TextBox ID="Minimum" RunAt="server" />
<asp:TextBox ID="Maximum" RunAt="server" />

<asp:CompareValidator
  ControlToValidate="Maximum"
  ControlToCompare="Minimum"
  Type="Integer"
  Operator="GreaterThanEqual"
  ErrorMessage="Invalid maximum"
  Display="static"
  RunAt="server"
/>
<asp:TextBox ID="Password1" TextMode="Password" RunAt="server" />
<asp:TextBox ID="Password2" TextMode="Password" RunAt="server" />

<asp:CompareValidator
  ControlToValidate="Password2"
  ControlToCompare="Password1"
  Type="String"
  Operator="Equal"
  ErrorMessage="Mismatch"
  Display="static"
  RunAt="server"
/>

RegularExpressionValidator

<asp:TextBox ID="Quantity" RunAt="server" />

<asp:RegularExpressionValidator
  ControlToValidate="Quantity"
  ValidationExpression="^\d+$" 
  ErrorMessage="Digits only"
  Display="static"
  RunAt="server"
/>
 
<asp:TextBox ID="EMail" RunAt="server" />

<asp:RegularExpressionValidator
  ControlToValidate="EMail"
  ValidationExpression="^[\w\.-]+@[\w-]+\.[\w\.-]+$"
  ErrorMessage="Invalid e-mail address"
  Display="static"
  RunAt="server"
/>
 
 

CustomValidator

<asp:TextBox ID="Amount" RunAt="server" />

<asp:CustomValidator
  ControlToValidate="Amount"
  ClientValidationFunction="__validateAmount"
  OnServerValidate="ValidateAmount"
  ErrorMessage="Amount must be a multiple of 10"
  Display="static"
  RunAt="server"
/>
    .
    .
    .
<script language="JavaScript"> 
<!--
  function __validateAmount (source, args)
  {
      args.IsValid = (args.Value % 10 == 0);
  }
-->
</script>

<script language="C#" runat="server"> 
  void ValidateAmount (Object sender, ServerValidateEventArgs e)
  {
      try {
          e.IsValid = (Convert.ToInt32 (e.Value) % 10 == 0);
      }
      catch (FormatException) {
          // In case a non-numeric value is entered
          e.IsValid = false;
      }
  }
</script>

ValidationSummary

 Collects error messages in a separate control
 
<asp:TextBox ID="UserName" RunAt="server" />

<asp:RequiredFieldValidator
  ControlToValidate="UserName"
  ErrorMessage="The user name can't be blank"
  Display="none" 
  RunAt="server"
/>

<asp:TextBox ID="Password" TextMode="Password" RunAt="server" />

<asp:RequiredFieldValidator
  ControlToValidate="Password"
  ErrorMessage="The password can't be blank"
  Display="none"
  RunAt="server"
/>

<asp:RegularExpressionValidator
  ControlToValidate="Password"
  ValidationExpression=".{8,}"
  Display="none"
  ErrorMessage="The password must contain at least 8 characters"
  RunAt="server"
/>

<asp:ValidationSummary
  DisplayMode="BulletList" 
  HeaderText="This page contains the following errors"
  RunAt="server"
/>

Spammer Example

 

<html>
  <head>
    <style>
    <!--
      body { font: 10pt verdana };
      table { font: 10pt verdana };
      input { font: 10pt verdana };
    -->
    </style>
  </head>
  <body>
    <table cellpadding="4" border="1">
      <tr bgcolor="yellow">
        <td>
Hi! We're Spammers, Incorporated. If you'll provide us with an e-mail
address, we'll clog your in-box with e-mail. Leave a snail mail address
and we'll bombard you with paper mail, too. If you're a totally
trusting person, type in a credit card number. We'll use it to defray
office costs next month.
        </td>
      </tr>
    </table>
    <h3>Yes, I want to be spammed. Sign me up now!</h3>
    <form runat="server">
      <table cellpadding="4">
        <tr>
          <td align="right">
            Name
          </td>
          <td>
            <asp:TextBox ID="Name" RunAt="server" />
          </td>
          <td>
            <asp:RequiredFieldValidator
              ControlToValidate="Name"
              ErrorMessage="Please enter your name"
              Display="dynamic"
              RunAt="server"
            />
          </td>
        </tr>
        <tr>
          <td align="right">
            E-Mail Address
          </td>
          <td>
            <asp:TextBox ID="EMail" RunAt="server" />
          </td>
          <td>
            <asp:RequiredFieldValidator
              ControlToValidate="EMail"
              ErrorMessage="Please enter your e-mail address"
              Display="dynamic"
              RunAt="server"
            />
            <asp:RegularExpressionValidator
              ControlToValidate="EMail"
              ValidationExpression="^[\w\.-]+@[\w-]+\.[\w\.-]+$"
              ErrorMessage="Invalid e-mail address"
              Display="dynamic"
              RunAt="server"
            />
          </td>
        </tr>
        <tr>
          <td align="right">
            Address
          </td>
          <td>
            <asp:TextBox ID="Address" RunAt="server" />
          </td>
          <td>
          </td>
        </tr>
        <tr>
          <td align="right">
            City
          </td>
          <td>
            <asp:TextBox ID="City" RunAt="server" />
          </td>
          <td>
          </td>
        </tr>
        <tr>
          <td align="right">
            State
          </td>
          <td>
            <asp:DropDownList ID="StateList" RunAt="server">
              <asp:ListItem Text="AL" RunAt="server" />
              ...
		 <asp:ListItem Text="WY" RunAt="server" />
            </asp:DropDownList>
          </td>
          <td>
          </td>
        </tr>
        <tr>
          <td align="right">
            Zip
          </td>
          <td>
            <asp:TextBox ID="ZipCode" RunAt="server" />
          </td>
          <td>
            <asp:RegularExpressionValidator
              ControlToValidate="ZipCode"
              ValidationExpression="^(\d{5}|\d{5}\-\d{4})$"
              ErrorMessage="Invalid zip code"
              Display="dynamic"
              RunAt="server"
            />
          </td>
        </tr>
        <tr>
          <td align="right">
            Credit Card Number
          </td>
          <td>
            <asp:TextBox ID="CreditCardNumber" RunAt="server" />
          </td>
          <td>
            <asp:RegularExpressionValidator
              ControlToValidate="CreditCardNumber"
              ValidationExpression="^[\d\-]{15,20}$"
              ErrorMessage="Invalid card number"
              Display="dynamic"
              RunAt="server"
            />
          </td>
        </tr>
        <tr>
          <td>
          </td>
          <td>
            <asp:Button Text="Sign Me Up" OnClick="OnSignMeUp"
              RunAt="server" />
          </td>
          <td>
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

<script language="C#" runat="server">
  void OnSignMeUp (Object sender, EventArgs e)
  {
      if (IsValid) {
          StringBuilder sb = new StringBuilder ("Thanks.aspx?Name=", 256);
          sb.Append (Name.Text);
          sb.Append ("&EMail=");
          sb.Append (EMail.Text);

          string address = Address.Text;
          string city = City.Text;
          string state = StateList.SelectedItem.Text;
          string zip = ZipCode.Text;

          if (address.Length > 0 && city.Length > 0 && zip.Length > 0) {
              sb.Append ("&Address=");
              sb.Append (address);
              sb.Append ("&City=");
              sb.Append (city);
              sb.Append ("&State=");
              sb.Append (state);
              sb.Append ("&ZipCode=");
              sb.Append (zip);
          }

          string number = CreditCardNumber.Text;

          if (number.Length > 0) {
              sb.Append ("&CreditCardNumber=");
              sb.Append (number);
          }

          Response.Redirect (sb.ToString ()); 
      }
  }
</script>
--------
<%@ Page Language="C#" %>

<html>
  <body>
    Here's the information you entered:<br><br>
    <ul>
      <%
        Response.Write ("<li>Name: " + Request["Name"]);
        Response.Write ("<li>E-mail address: " + Request["EMail"]);

        if (Request["Address"] != null) {
            StringBuilder sb =
                new StringBuilder ("<li>Address: ", 64);
            sb.Append (Request["Address"]);
            sb.Append (", ");
            sb.Append (Request["City"]);
            sb.Append (", ");
            sb.Append (Request["State"]);
            sb.Append (" ");
            sb.Append (Request["ZipCode"]);
            Response.Write (sb.ToString ());
        }

        if (Request["CreditCardNumber"] != null)
            Response.Write ("<li>Credit card number: " +
                Request["CreditCardNumber"]);
      %>
    </ul>
    Thanks for signing up with Spammers, Inc.!
  </body>
</html>

<html>
  <body>
    <h1>Conditional Validation Demo</h1>
    <hr>
    <form runat="server">
      <table cellpadding="4">
        <tr>
          <td align="right">
            Name
          </td>
          <td>
            <asp:TextBox ID="Name" RunAt="server" />
          </td>
          <td>
            <asp:RequiredFieldValidator
              ControlToValidate="Name"
              ErrorMessage="Please enter your name"
              Display="dynamic"
              Color="red"
              RunAt="server"
            />
          </td>
        </tr>
        <tr>
          <td align="right">
            E-Mail Address
          </td>
          <td>
            <asp:TextBox ID="EMail" RunAt="server" />
          </td>
          <td>
            <asp:RequiredFieldValidator
              ControlToValidate="EMail"
              ErrorMessage="Please enter your e-mail address"
              Display="dynamic"
              Color="red"
              Enabled="false"
              ID="EMailRequiredValidator"
              RunAt="server"
            />
            <asp:RegularExpressionValidator
              ControlToValidate="EMail"
              ValidationExpression="^[\w\.-]+@[\w-]+\.[\w\.-]+$"
              ErrorMessage="Invalid e-mail address"
              Display="dynamic"
              Color="red"
              Enabled="false"
              ID="EMailExpressionValidator"
              RunAt="server"
            />
          </td>
        </tr>
        <tr>
          <td>
          </td>
          <td>
            <asp:CheckBox ID="Confirm"
              Text="E-mail my confirmation"
              OnCheckedChanged="OnCheckBoxClicked"
              AutoPostBack="true" RunAt="server" />
          </td>
          <td>
          </td>
        </tr>
        <tr>
          <td>
          </td>
          <td>
            <asp:Button Text="Register" OnClick="OnRegister"
              RunAt="server" />
          </td>
          <td>
          </td>
        </tr>
      </table>
      <br><hr><br>
      <asp:Label ID="Output" RunAt="server" />
    </form>
  </body>
</html>

<script language="C#" runat="server">
  void OnCheckBoxClicked (Object sender, EventArgs e)
  {
      EMailRequiredValidator.Enabled = Confirm.Checked;
      EMailExpressionValidator.Enabled = Confirm.Checked;
  }

  void OnRegister (Object sender, EventArgs e)
  {
      if (IsValid) {
          if (Confirm.Checked) {
              Output.Text =
                  "Confirmation will be e-mailed to " +
                  EMail.Text + ".";
          }
          else {
              Output.Text =
                  "At your request, no confirmation will " +
                  "be sent.";
          }
      }
  }
</script>

 


Copyright chris wild 1999-2004.
For problems or questions regarding this web contact [Dr. Wild].
Last updated: December 22, 2003.