我用VS2012 做一个简单的注册验证,身份证前3位代表省份编号,各省份的相关信息存在数据库里。现在要对此进行验证(还没有进行身份证号其他方面的验证),用微软自带的自定义控件CustomValidator的ClientValidationFunction实现,即
<asp:CustomValidator ID="cvIdentity" runat="server" ControlToValidate="txtIdentity" ErrorMessage="身份证号错误" SetFocusOnError="True"
OnServerValidate="cvIdentity_ServerValidate" ClientValidationFunction="Identity_ClientValidate"></asp:CustomValidator>
客户端验证函数定义如下:
function Identity_ClientValidate(source, args)
{
var str = args.Value;
if(str.length < 3)
{
if (str.length != 0)
{
args.IsValid = false;
}
return;
}
var xmlHttp = new XMLHttpRequest();
var url = "CheckProCode.aspx" + "?ID=" + str;
xmlHttp.onreadystatechange = function ()
{
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
if (xmlHttp.responseText == "身份证号错误")
{
args.IsValid = false;
}
}
}
xmlHttp.open("GET", url, true);
xmlHttp.timeout = 10000;
xmlHttp.send(null);
}
请求页面CheckProCode.aspx就是连接数据库,返回responseText,如下:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string ConStr = WebConfigurationManager.ConnectionStrings["SqlConString"].ToString();
string code = Request.QueryString["ID"].Substring(0, 3);
SqlConnection Con = new SqlConnection(ConStr);
Con.Open();
SqlCommand Cmd = new SqlCommand("SELECT * FROM PROVINCE WHERE DigitalCode =" + code, Con);
SqlDataReader dtrSql = Cmd.ExecuteReader();
if (!dtrSql.HasRows)
{