CustomValidator自定义控件的使用

CustomValidator自定义控件有2种方式来进行验证:

 

第一种(客户端进行验证):ClientValidationFunction属性调用客户端JS的代码来进行验证,参数source为CustomValidator控件对象,参数args为CustomValidator控件传递过来的相关数据。

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomDefault.aspx.cs" Inherits="第3章_自定义验证控件_CustomDefault" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>


    <script type="text/javascript">
    function myfun(source,args)
    {
        //注意大小写
        if(args.Value.length < 6 || args.Value.length > 10)
        {
            //window.alert(source.id);
            //window.alert(source.errormessage);
            //window.alert(args.Value);
            args.IsValid = false; //验证未通过
        }
    }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="长度应大于6位小于10位!"  ClientValidationFunction="myfun">
        </asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>

</html>

 

第二种(服务器端进行验证):

.aspx文件代码:

        <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="长度应大于6位小于10位!" 
onservervalidate="CustomValidator1_ServerValidate1">
        </asp:CustomValidator>

 

.cs文件代码:

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (args.Value.Length > 10)
            args.IsValid = false;
        else
            args.IsValid = true;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值