62,268
社区成员
发帖
与我相关
我的任务
分享<span>用户名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1" Display="None"
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" Display="Dynamic">用户名不能为空</asp:RequiredFieldValidator>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="提交" />
</span>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
Match match = Regex.Match(args.Value,"^[\u4e00-\u9fa5A-za-z0-9_-]+$");
args.IsValid = match.Success;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (CustomValidator1.IsValid == false)
{
Label1.Text = "你输入了非法字符";
}
else if (getTextBoxLength(TextBox1.Text) >= 4 && getTextBoxLength(TextBox1.Text) <= 20)
{
Label1.Text = "通过验证";
}
else
{
Label1.Text = "只能输入4-20位字符";
}
}
//获取文本框字符串长度
//Textbox控件的Text是string类型,该类型是unicode编码,只需获取中文的unicode值范围
//然后对string逐个进行分析,如果在中文unicode值范围内就加2,否则就加1
//中国、日本和韩国的象形文字(总称CJK)占用了Unicode字符从0x3000到0x9FFF的代码
int getTextBoxLength(string textBoxStr)
{
int nlength = 0;
for (int i = 0; i < textBoxStr.Length; i++)
{
if (textBoxStr[0] >= 0x3000 && textBoxStr[i] <= 0x9FFF)
{
nlength += 2;
}
else
{
nlength++;
}
}
return nlength;
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
string inputs = args.Value;
if (string.IsNullOrEmpty(inputs))
{
CustomValidator1.ErrorMessage = "用户名不能为空";
args.IsValid = false;
return;
}
else if (!Regex.Match(args.Value, "^[\u4e00-\u9fa5A-za-z0-9_-]+$").Success)
{
CustomValidator1.ErrorMessage = "你输入了非法字符";
args.IsValid = false;
return;
}
else if (!(getTextBoxLength(inputs) >= 4 && getTextBoxLength(inputs) <= 20))
{
CustomValidator1.ErrorMessage = "只能输入4-20位字符";
args.IsValid = false;
return;
}
else
{
args.IsValid = true;
return;
// 如果设置了IsValid=true就不能显示"通过验证"了。还是用Label吧
}
}