MaxLengthValidation Control


Hi guys, I was thinking that lots of developers are not able to solve the problem of validate Max character length for a multi textbox. Lots of developers are using server side code or writing the javascript to validate the maximum character length of the multi textbox control. So, please go ahead and use my MaxLengthValidation control and need not to write single line of code. You can use it like other validation control. Let me know if you guys have any query. 

Before you build MaxLengthValidation control you need to perform the following steps:
  1. Create a class that inherits from BaseValidator class.
  2. Add a MaxLength property.
  3. Override the OnPreRender event.
  4. Generate required script to the validation
  5. Override the EvaluateIsValid() method.
Step 1:

Create a class that inherits from BaseValidator class (available in System.Web.UI.WebControls namespace).

public class MaxLengthValidator : BaseValidator

Step 2:

Add a MaxLength property to the class:

private Int32 _MaxLength = -1;
public Int32 MaxLength
{
    get { return _MaxLength; }
    set
    {
        if (_MaxLength < 1)
        {
            throw new Exception("Invalid Length. Minimum number of characters are 1");
        }
        _MaxLength = value;
    }
}

Step 3:

Override the OnPreRender event.

protected override void OnPreRender(EventArgs e)
{
    if (this.DetermineRenderUplevel() && this.EnableClientScript)
    {
        Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "CheckLength");
        this.GenerateValidation();
    }
    base.OnPreRender(e);
}

Step 4:

Generate required script to validate the MaxLength.

protected void GenerateValidation()
{
    TextBox txt = (TextBox)this.FindControl(this.ControlToValidate);
    StringBuilder sb = new StringBuilder();
    sb.Append(@"<script type=""text/javascript"">function CheckLength(ctrl){");
    sb.Append(@"var txtControl = document.getElementById(document.getElementById(ctrl.id).controltovalidate);");
    sb.Append(@"var MaxValue = " + _MaxLength + ";");
    sb.Append(@"if(MaxValue < txtControl.value.length){");
    sb.Append(@"return false; }");
    sb.Append(@"else {return true;} ");
    sb.Append(@"}</script>");
    Page.ClientScript.RegisterClientScriptBlock(GetType(), "JSScript", sb.ToString());
}

Step 5:

Override the EvaluateIsValid method:

protected override bool EvaluateIsValid()
{
    return this.IsValid;
}


Similar Articles