Search code examples
c#asp.netvalidationmodel-view-controller

asp.net C# get textbox lenght from backend


I would like to inform user if he is adding more character than he needs for a certain field.

my code behind :

if (txt1.txt.??? < X)
{
   alert(You exceed to the max amount of characters, max is X number);
}

Solution

  • To get the length of a textbox value from behind code.

    if(txt1.Text.Length < 11)
    {
     //Your code here
    }
    else
    {
      //Your Code here 
    }
    

    However, why don't you used a textbox masked extender like Ajax or a RegularExpressionValidator validation?

    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Enter valid Phone number" ControlToValidate="txt1" ValidationExpression="\d{10}" ValidChars="()-" ></asp:RegularExpressionValidator>