自定义验证控件CustomValidator

客户端

<%@ Page Language="C#"   CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 validateCity(source,args)
     {
        var str =args.Value;
        if (str.length<=6)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="小于6位"  ClientValidationFunction="validateCity" ControlToValidate="TextBox1"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

 

服务器端

private void CustomValidator1_ServerValidate_1(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
  {
   string lname=args.Value;
   if(DB.judge(lname))
   {
    args.IsValid=false;

   
   }
   else
   {
    args.IsValid=true;
   }
  }

定义的类中的静态方法
 public static bool judge(string lname)
  {
   SqlConnection con =DB.creatconnection();
   con.Open();
   SqlCommand cmd =new SqlCommand("select count(*) from login where lname='"+lname+"'",con );
   int count =Convert.ToInt32(cmd.ExecuteScalar());
   if (count>0)
   {
    return true;
 
   
   }
   else {
   
        return false;
   }

  

其他验证控件比较简单,在这里就不在多说了,有一点需要提示一下,就是在后台代码中如果验证结束,我们可以通过

  if(page.isValid){}

 判断即可!

 电话号码手机验证: <asp:RegularExpressionValidator ID="RegularExpressionValidator1"
                                 ControlToValidate="txtel" runat="server" ErrorMessage="联系电话输入有误..."
                                 SetFocusOnError="True" ValidationExpression="((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)"></asp:RegularExpressionValidator>

 

邮箱验证:  <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
                                 ControlToValidate="txemail" ErrorMessage="邮箱地址输入有误..."
                                 ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

posted @ 2011-02-22 20:12  双魂人生  阅读(1676)  评论(0编辑  收藏  举报