1.创建自定义验证控件:新建LengthValidator类并继承BaseValidator
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; namespace MyControl { public class lengthValidator : BaseValidator { public int MaximumLength { get; set; } protected override bool EvaluateIsValid() { string value = this.GetControlValidationValue(this.ControlToValidate); if (value.Length > MaximumLength) return false; else return true; } } }
BaseValidator类有两个重要的方法:
1)GetControlValidationValue方法获取被验证控件的值;
2)EvaluateIsValid方法检验控件的值是否有效,有效时返回true,无效返回false。
2.新建LengthValidatorTest页面用LengthValidator控件验证长度
LengthValidator创建后编译一下工具箱最上面即出现LengthValidator,只要把控件拖到要使用的页面即可
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LengthValidatorTest.aspx.cs" Inherits="WebApplication1.LengthValidatorTest" %> <%@ Register Assembly="WebApplication1" Namespace="MyControl" TagPrefix="cc1" %> <!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> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <cc1:lengthValidator ID="LengthValidator1" runat="server" ControlToValidate ="TextBox1" Display ="Dynamic" MaximumLength="10" Text ="长度不能大于10个字符"></cc1:lengthValidator> <asp:Button ID="Button1" runat="server" Text="提交" onclick="Button1_Click" /> </div> </form> </body> </html>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class LengthValidatorTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (Page.IsValid) { //.... } } } }
注:自定义验证控件有错误时并不会阻止页面提交,所以提交数据必须用Page.IsValid检查一下表单是否都通过验证。