前些天在做注册页面的验证的时候,用了下ASP.net的验证控件,有一些体会,特写下这篇博客,如果有朋友有不同ideas,欢迎大家留言。

①、数据格式验证控件(RegularExpressionValidator)

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="此用户名已注册过" ControlToValidate = "txtName" ValidationExpression = "\S+@\S+\.\S+">
</asp:RegularExpressionValidator> 

通过自定义正则表达式,与需验证的控件进行模式匹配。

以前面这段代码为例:

ErrorMessage属性表示当验证不合法时,出现错误的信息;

ControlToValidate属性表示需验证的控件ID;

ValidationExpression属性指定为验证条件的正则表达式;

 

在这里贴上常用正则表达式字符及其含义:

View Code
编号    正则表达式字符    含义
1 [……] 匹配括号中的任何一个字符
2 [^……] 匹配不在括号中的任何一个字符
3 \w 匹配任何一个字符(a~z、A~Z和0~9)
4 \W 匹配任何一个空白字符
5 \s 匹配任何一个非空白字符
6 \S 与任何非单词字符匹配
7 \d 匹配任何一个数字(0~9)
8 \D 匹配任何一个非数字(^0~9)
9 [\b] 匹配一个退格键字符
10 {n,m} 最少匹配前面表达式n次,最大为m次
11 {n,} 最少匹配前面表达式n次
12 {n} 恰恰匹配前面表达式n次
13 ? 匹配前面表达式0或1次 {01}
14 + 至少匹配前面表达式1次 {1,}
15 * 至少匹配前面表达式0次 {0,}
16 | 匹配前面表达式或后面表达式
17 (…) 在单元中组合项目
18 ^ 匹配字符串的开头
19 $ 匹配字符串的结尾
20 \b 匹配字符边界
21 \B 匹配非字符边界的某个位置

 

同时,列举几个常用的正则表达式:(有些是我自己用过的,有些是网上找的资料)

View Code
验证电子邮件:
"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”
\S+@\S+\.\S+


验证网址:
"\S+://\S+\.\S+”


验证邮政编码:"\d{6}”


其他常用正则表达式:
表示0~9十个数字:"[0-9]”

表示任意个数字:"\d*”

表示中国大陆的固定电话号码:"\d{3,4}-\d{7,8}”

验证由两位数字、一个连字符再加5位数字组成的ID号:"\d{2}-\d{5}”

 

②、自定义验证控件(CustomValidator)

Default页面:

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="此用户名已注册过" ControlToValidate = "txtName" OnServerValidate ="ValidateName">
</asp:CustomValidator>

Defalult.cs页面:

View Code
 public void ValidateName(Object sender, ServerValidateEventArgs args)
{
SqlConnection myConn = new SqlConnection("Data Source=(local);Initial Catalog=Csharp;Integrated Security=True");
myConn.Open();
SqlCommand myCmd = new SqlCommand("select use_account from users", myConn);
SqlDataAdapter myDa = new SqlDataAdapter(myCmd);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)
{
if (args.Value.ToString() == myDs.Tables[0].Rows[i][0].ToString())
{
args.IsValid = false;
break;
}
else
{
args.IsValid = true;
}
}
}

 

通过自定义服务器端的函数代码,与前台验证控件关联,形成一种假客户端—当前页面验证的效果。

以上面前台验证控件这段代码为例:

ErrorMessage属性表示当验证不合法时,出现错误的信息;

ControlToValidate属性表示需验证的控件ID;

OnServerValidate属性表示与自定义函数相关联,以在服务器上执行验证;

 

效果如下:

posted on 2011-11-26 09:14  guolebin7  阅读(1422)  评论(5编辑  收藏  举报