Home » ASP.Net

ASP.Net Validating for Max Number of Characters in a TextBox. C# Sample

1. September 2010 by jdelpay 0 Comments

Let's say you have a Text Box = TextBox1 (textMode=MultiLine etc...) and you want to validate/Limit the number of character entered by a user

Do this:

  1. Add a customField Validator.
  2. In the customValidator properties: ErrorMessage = "Your Error Message" ControlToValidate ="control you want to validate"
  3. Select the Event button or double click the CustomValidator on the page.
  4. In the code behind Enter the following:
protected void CustomValidator1_ServerValidate
(object source, ServerValidateEventArgs args)
    {
        if (TextBox1.Text.Length > 10)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }

To avoid making a trip to the server and have instant validation when tabbing or moving to another field do this.

  1. Return to the CustomValidator control properties and add under Behavior:
    ClientValidationFunction = validateComments (or whatever text you want to call it)
  2. In your aspx file add a ScriptManager from the Ajax Extensions.
    Then add a new Item and select JScript File
  3. In the script file add the following function.

Voila! if you using a master page add the SciptManager in your master page. Hope this helped.


function validateComments(sender, args) 
{
 
    if (args.Value.length > 10)
        args.IsValid = false;
    else
        args.IsValid = true;
}
Also, Reference the file in your script manager(see below after the function).
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Scripts>
    <asp:ScriptReference Path="~/validateComments.js" />
    </Scripts>
    </asp:ScriptManager>