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();
}
}
|