Saturday, August 9, 2014

TextBox characters limitation using Regular Expression and JavaScript JQuery

Some times its important to restrict the characters limit of any text box in your ASP.NET site to prevent some of your action or any thing others. But how to do that. Generally we can do this in 3 ways.
  • Check in code behind
  • Use regular expression
  •  JavaScript or jQuery
Before checking all these methods first create a new project and add 3 pages for 3 methods.

Check in code behind :

In the first web form add a new TextBox and a new Button. Make the TextBox multiline and generate a Click event of the button. In the Click event write down the following code.

protected void btnSubmit_Click(object sender, EventArgs e)
{
 if (txtMessage.Text.Length > 20)
 {
  lblMessage.Text = "Out of 20 characters !";
  lblMessage.ForeColor = System.Drawing.Color.Red;
 }
 else
 {
  /* Do your actoin */
 }
}


Using Regular Expression :

Using the regular expression you can do this also. Just use the "^[\s\S]{0,20}$" expression to validate the TextBox. Follow the following code.

Using Regular Expression




And now the last and efficient one to check the maximum characters.

Using JavaScript or JQuery:

Using JavaScript and JQuery you will get the best result to check the maximum characters of a TextBox with the help of MaxLength.min.js. And one extra thing you have to do. have to add the jqery.min.js API of JQuery, which we will get from either JQuery or Google API center.
Use the following code to check the maximum characters.

ASPX Code :

Max charecter in a Text Box

Using Javascript


JavaScript Code :

    
    

aRun your project and enjoy.... :)
Download the fill source code here.

0 comments:

Post a Comment

Popular Posts

Pageviews