Home   Cover Cover Cover Cover
 

Plausibilitätsprüfung

Web-Seite

../../solutions/6/Date.aspx
<%@ Page Language="C#" Inherits="DateCheck" Src="Date.aspx.cs" %>
<html>
  <head>
    <title>Check a text field for a legal date value</title>
  </head>
  <body>
    <h2>Enter a date</h2>
    <p>e.g. 12/24/02 or 12-Dec-2002</p>
    <form method="post" Runat="server">
      <asp:TextBox ID="date" AutoPostBack="true" OnTextChanged="HandleText" Runat="server" />
      <asp:CustomValidator ID="validator" ControlToValidate="date"
        OnServerValidate="CheckDate" Text="wrong date format" Runat="server" />
    </form>
  </body>
</html>

Hintergrundcode

../../solutions/6/Date.aspx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public class DateCheck : Page {
  protected TextBox date;
  protected CustomValidator validator;
  
  char ch;
  int pos;
  string[] months = 
    {"Apr", "Aug", "Dec", "Feb", "Jan", "Jul", "Jun", "Mar", "May", "Nov", "Oct", "Sep"};
  
  //----- read the next character from date.Text[pos]
  void NextCh() {
    if (pos >= date.Text.Length) ch = '\uffff';
    else ch = (char)date.Text[pos++];
  }
  
  //----- read a sequence of digits from date.Text[pos]
  int NextNum() {
    int val = 0;
    while (Char.IsDigit(ch)) {
      val = 10 * val + (ch - '0');
      NextCh();
    }
    return val;
  }
  
  //----- read a sequence of letters from date.Text[pos]
  string NextName() {
    StringBuilder s = new StringBuilder();
    while (Char.IsLetter(ch)) {
      s.Append(ch);
      NextCh();
    }
    return s.ToString();
  }
  
  //----- check if date.Text holds a valid date
  public void CheckDate(object sender, ServerValidateEventArgs e) {
    try {
      pos = 0; NextCh();
      int n1, n2, n3;
      n1 = NextNum();
      if (ch == '/') {  // e.g. 10/12/02
        NextCh();
        n2 = NextNum();
        if (ch != '/') throw new FormatException();
        NextCh();
        n3 = NextNum();
        if (n1 == 0 || n1 > 12 || n2 == 0 || n2 > 31 || n3 == 0 || n3 > 2100)
          throw new FormatException();
      } else if (ch == '-') {  // e.g. 12-Oct-2002
        NextCh();
        string s = NextName();
        if (Array.BinarySearch(months, s) < 0) throw new FormatException();
        if (ch != '-') throw new FormatException();
        NextCh();
        n3 = NextNum();
        if (n1 == 0 || n1 > 31 || n3 == 0 || n3 > 2100) throw new FormatException();
      } else {
        throw new FormatException();
      }
      e.IsValid = true;
    } catch (FormatException) {
      e.IsValid = false;
    }
  }
  
  //----- Only postback events cause validation => call Validate manually
  public void HandleText(object sender, EventArgs e) {
    Page.Validate();
  }
}

Ausführung

Klicken Sie hier.