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 函数
<script language="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. 客户端和服务端同时验证
将上面的两部分代码合并可以了
希望这篇
CustomValidatord 验证控件使用的文章能够对您有所帮助,如果您觉得这篇网站维护教程有用的话,别忘了推荐给您的朋友哦!如果您有好的经验方法,不妨拿出来和大家一起分享:假如每个人都拿出一个经验,那么我们都将额外的获取一堆他人的经验。
请记住本站永久域名:(黑客防线网安服务器维护方案维护基地)Www.Rongsen.Com.Cn