using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;

namespace Example.第4章._40.如何创建自定义验证控件
{
	/// <summary>
	/// WebCustomControl1 的摘要说明。
	/// </summary>
	[DefaultProperty("Text"), 
		ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
	public class WebCustomControl1 : System.Web.UI.WebControls.RequiredFieldValidator
	{
		[Bindable(true),
		Category("Appearance"),
		Description( "用于指定被验证控件输入的字符位数" ),
		DefaultValue(0)]
		public int len
		{
			get
			{
				object lens = this.ViewState["len"];
				if (lens != null)
					return Convert.ToInt32(this.ViewState["len"]);
				else
					return 0;
			}
			set
			{
				ViewState["len"] = value;
			}
		}

		/// <summary> 
		/// 将此控件呈现给指定的输出参数。
		/// </summary>
		/// <param name="output"> 要写出到的 HTML 编写器 </param>
		protected  override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			if(Page.IsPostBack)
			{
				if (this.Enabled)
				{
					string ValidateID = this.ControlToValidate;
					string context = ((TextBox)Page.FindControl(ValidateID)).Text.Trim();
					if(context.Length != this.len)
					{
						this.IsValid = false;
					}
				}
			}
		}
	}
}
