为了保证用户输入的正确,常常要用到正则表达式,而最常见的就是日期的正则表达式了。
我们可以在前台编写JavaScript控制,也可以在后台控制。
我需要让用户在生命周期选项里输入格式为年月日,在播放时段中的输入格式为时分秒。
下面是我在后台编写的控制播放时段格式的代码:

Code
1
//播放时段正则表达式(24小时制----时分秒)
2
string rTime = @"(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])";
3
RegexStringValidator myRegexValidator = new RegexStringValidator(rTime);
4
5
if (myRegexValidator.CanValidate(Tdate.GetType()))
6
{
7
try
8
{
9
myRegexValidator.Validate(Tdate);
10
isType = true;
11
}
12
catch (ArgumentException ex)
13
{
14
isType = false;
15
}
16
}
17
if (myRegexValidator.CanValidate(Tdatee.GetType()))
18
{
19
try
20
{
21
myRegexValidator.Validate(Tdatee);
22
isTypee = true;
23
}
24
catch (ArgumentException ex)
25
{
26
isTypee = false;
27
}
28
}
29
//添加播放时段验证日期
30
if (cmd == "添加播放时段")
31
{
32
if (isType != true)
33
{
34
Response.Write("<script>alert('播放时段起始时间格式错误!格式形如--08:30:22');</script>");
35
return;
36
}
37
else if (isTypee != true)
38
{
39
Response.Write("<script>alert('播放时段结束时间格式错误!格式形如--08:30:22');</script>");
40
return;
41
}
42
}
43
当然了,为了最大程度上避免用户输入错误,我们一般选用calendar控件来让用户选择时间,我们可以选用系统自带的calendar控件,也可自己编写,我这里是用的公司原先的一个calendar控件,我会提供源码供大家下载。
这里要求用户选择完起始时间后光标自动跳到结束时间选择框,且控制用户只能选择起始时间之后的结束时间。
前台代码如下:

Code
1
<SCRIPT language="JavaScript" type="text/javascript" src="../javascript/sel_date.js"></SCRIPT>
2
3
4
<tr id="trLifeBT">
5
<td> 生命周期起始时间:<input id="Cdate" class="limit2" maxlength="22" name="Cdate" onfocus="new WdatePicker(this,'%Y-%M-%D',true,'whyGreen')" maxdate="#F{$('Cdatee').value}" onpicked="$('Cdatee').onfocus()" size="10" type="text" value="<%=Cdate%>" /></td>
6
</tr>
7
<tr id="trLifeET">
8
<td> 生命周期结束时间:<input id="Cdatee" class="limit2" maxlength="22" name="Cdatee" onfocus="new WdatePicker(this,'%Y-%M-%D',true,'whyGreen')" mindate="#F{$('Cdate').value}" size="10" type="text" value="<%=Cdatee%>" /></td>
9
</tr>
10
11
<tr id="trDisplayBT">
12
<td style="height: 22px"> 播放时段起始时间:<input name="Tdate" type="text" onfocus="new WdatePicker(this,'%h:%m:%s',true,'whyGreen')" maxdate="#F{$('Tdatee').value}" onpicked="$('Tdatee').onfocus()" class="limit2" id="Tdate" value="<%=Tdate%>" size="10" maxlength="8"></td>
13
</tr>
14
<tr id="trDisplayET">
15
<td style="height: 22px"> 播放时段结束时间:<input name="Tdatee" type="text" onfocus="new WdatePicker(this,'%h:%m:%s',true,'whyGreen')" mindate="#F{$('Tdate').value}" class="limit2" id="Tdatee" value="<%=Tdatee%>" size="10" maxlength="8"></td>
16
</tr>
我用到的calendar控件js源码下载:
/Files/gutiaron/JavaScript/sel_date.rar