简体   繁体   中英

Restricting characters entered in textbox using Javascript

我需要验证一个文本框,该文本框应只允许某些字符,并且在达到限制后,该文本框应不允许在其中输入字符。可以通过Javascript完成,但不知道该怎么做。

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>

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 = ".*";
 }

尝试jQuery-使用maxLength的 数值 (如果可以的话,在某些版本的Firefox中可以忽略它)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM