Abilash
Abilash

Reputation: 113

Restricting characters entered in textbox using Javascript

I need to validate a textbox that it should allow only certain characters and after the limit is reached the textbox should not allow entering characters in it.It can be done by Javascript but dont know how to do.. Anyone please help..

Upvotes: 1

Views: 6637

Answers (3)

sweets-BlingBling
sweets-BlingBling

Reputation: 4422

Here I have provided a 2 solutions: 1)js function 'TextLimit':which keeps a check on count of characters typed into the textbox. 2)maxlength attribute: specifies the maximum length (in characters) of an input field.

<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script>
function TextLimit(){
    var text = document.getElementById('myinput');
   if (text.value.length > 10){
        alert('You exceeded the limit');
        text.value = text.value.substring(0,10);
    }
}  
</script>
</HEAD>
<BODY>
<input name="myinput" type="text" value='' id="myinput" onkeyup="TextLimit()">
<br>
//this is using the maxlength attribute of textbox
<input type="text" name="inputtext" maxlength="10">
</BODY>
</HTML>

Upvotes: 2

mikek3332002
mikek3332002

Reputation: 3562

Single Line textboxes automatically follow the maxLength attribute.

Dynamicdrive.com has a javascript script that enforces max length on multiline by truncating the text entered to max length.

One way to add the required attributes to every control is by overiding the render method of the control.

You can also do it with a RegularExpressionValidator:

RegularExpressionValidator regexValidator = new RegularExpressionValidator();
if (this.MaxLength > 0)
{
    regexValidator.ValidationExpression = ".{0," + <textbox>.MaxLength + "}";
 }
 else
 {
     regexValidator.ValidationExpression = ".*";
 }

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

Try jQuery - numeric with maxLength (if you're ok with it being ignored on certain versions of firefox).

Upvotes: 0

Related Questions