using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; namespace MyCustomControls { [ValidationPropertyAttribute("Text")] public class RestrictedTextArea : CompositeControl { TextBox textbox = new TextBox(); CustomValidator validator = new CustomValidator(); public RestrictedTextArea() { // Configure the textbox this.textbox.TextMode = TextBoxMode.MultiLine; this.Controls.Add(textbox); // Configure the validator this.validator.Text = "X"; this.validator.Style.Add("font-weight", "bold"); // The event handler will be created when we get to the MaxLength property this.validator.ServerValidate += new ServerValidateEventHandler(validator_ServerValidate); this.Controls.Add(validator); // Conifgure some CompositeControl properties this.Width = new Unit(155); this.Height = new Unit(30); } bool customErrorMessage = false; public string ErrorMessage { set { this.validator.ErrorMessage = value; this.customErrorMessage = true; } } private string fieldName = ""; public string PrettyFieldName { get { return this.fieldName; } set { this.fieldName = value; } } public int MaxLength { get { return this.textbox.MaxLength; } set { this.textbox.MaxLength = value; this.textbox.Attributes.Add( "OnKeyUp", "if (this.value.length > " + value + ") { alert('Sorry! The max number of allowed characters is " + value + ".'); this.value = this.value.substring(0," + value + "); }"); } } void validator_ServerValidate(object source, ServerValidateEventArgs args) { if (this.textbox.Text.Length != 0 && this.textbox.Text.Length > this.textbox.MaxLength) { if (!this.customErrorMessage) this.validator.ErrorMessage = "Sorry! You're only allowed a max of " + this.textbox.MaxLength + " characters for the '" + this.fieldName + "' field. Your text has a size of " + this.textbox.Text.Length + " characters."; args.IsValid = false; } } public override Unit Height { get { return base.Height; } set { this.textbox.Height = base.Height = value; } } public override Unit Width { get { return base.Width; } set { double validatorWidth = 30; if (value.Value > validatorWidth) { base.Width = value; this.textbox.Width = new Unit(value.Value - validatorWidth); } } } public string Text { set { this.textbox.Text = value; } get { return this.textbox.Text; } } } }