3

I have a text box with label name Employee Id and a text box to provide employee id now to this text box i should set a validation to have a limit up to 5 numbers or characters if the user tries to enter more than 5 characters or numbers it should display an error message your maximum limit is only 5.

Employee ID*

here i have no button to the text box hence while entering only if the limit exceeds 5 it should display the error message before going to next text box.can you please help me out.

1
  • Is this web forms or mvc? Commented May 6, 2016 at 5:53

5 Answers 5

4

Below code will help you. Maximum and Minimum character length validation for 5 character.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox1" ID="RegularExpressionValidator1" ValidationExpression = "^[\s\S]{0,5}$" runat="server" ErrorMessage="Your maximum limit is only 5"></asp:RegularExpressionValidator> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox1" ID="RegularExpressionValidator1" ValidationExpression = "^[\s\S]{5,}$" runat="server" ErrorMessage="Minimum required limit is 5"></asp:RegularExpressionValidator> 
Sign up to request clarification or add additional context in comments.

Comments

2

In ASP.NET you will have validation controls, for this case you can use Regular Expression controller

<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox1" ID="RegularExpressionValidator1" ValidationExpression = "^[\s\S]{0,5}$" runat="server" ErrorMessage="Maximum 5 characters allowed."></asp:RegularExpressionValidator> 

If you are using HTML5 you can set a pattern also like below that also will show validation

<input type="text" maxlength="5" pattern=".{5,5}" class="text-center" autocomplete="off" id="yearofManufacture" required placeholder="Year of Manufacture"> 

In the second approach you don't need to add any plugins also

Comments

2

try this it will work

 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate ="TextBox2" ID="RegularExpressionValidator1" ValidationExpression = "^[\s\S]{0,5}$" runat="server" ErrorMessage="Maximum 5 characters allowed."></asp:RegularExpressionValidator> 

Comments

1

You can use JQuery Validation:

$("#myinput").rules( "add", { required: true, maxlength: 5, messages: { required: "Required input", minlength: jQuery.validator.format("Please, at most {0} characters are allowed") } }); 

You can include it in your project via Nuget or Visual Studio Nuget Manger

Follow this step by step Tutorial: JQuery Validation Tutorial

Comments

0

You can set the textBox.MaxLength=5; so the user can't actually write more than 5 characters, why would you need an error message? This should be enough.

Comments