前天市场部一个需求,录入时检测电话和邮件是否在数据库里存在,如果存在就在录入完成后就直接提示,而不是在保持时提示。
我想了一下用CustomValidator验证控件加Javascript代码可以轻松搞定。
当然解决这个问题的方法很多,我只写我所用的。
其实就是用ClientValidationFunction为javascript 验证函数(function)
CustomValidator控件允许用户自定义验证,可以在服务器端验证,可以在客户端验证,也可以在客户端和服务端同时验证
下面的例子是验证一个数能否被2整除
1.服务器端验证
在验证的时候会用到IsValid这个属性,根据IsValid的值(true/false)来判断是否通过页面验证。
a.拖放控件TextBox用于输入值;Button用于测试验证状态,IsValid为true触发Click事件;CustomValidator控制要验证的对象和验证事件等。
b.设置CustomValidator的属性这里设置ErrorMessage为Not an even number!,ControlToValidate为Text1
c.编写CustomValidator的ServerValidation事件
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
int num = int.Parse(args.Value);
args.IsValid = ((num%2)==0);
}
catch (Exception ex)
{
args.IsValid = false;
}
}
d.编写Button的Click事件
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("gouWuChe.aspx");
}
else
{
//提示
}
}
2.客户端验证
使用javascript function验证,并用设置ClientValidationFunction为javascript验证函数(function)
a.Javascript 函数
<scriptlanguage="javascript">
function ValidateNumber(source,args)
{
if(args.Value%2==0)
{
args.IsValid=true;
}
else
{
args.IsValid=false;
}
}
</script>
b.设置CustomValidator的属性这里设置ErrorMessage为请输入能被2整除的数,ControlToValidate为TextBox1, ClientValidationFunction为ValidateNumber
c.编写Button的Click事件
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("gouWuChe.aspx");
}
else
{
//提示
}
}
3.客户端和服务端同时验证
将上面的两部分代码合并可以了