Limit number of characters allowed in form input t

2019-01-02 20:48发布

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?

Below is the input field as part of my form:

<input type="text" id="sessionNo" name="sessionNum" />

Is it using something like maxSize or something like that?

9条回答
刘海飞了
2楼-- · 2019-01-02 21:19

According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.

Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway

查看更多
呛了眼睛熬了心
3楼-- · 2019-01-02 21:25

maxlength:

The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field will scroll appropriately. The default is unlimited.

<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />

However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.

查看更多
长期被迫恋爱
4楼-- · 2019-01-02 21:29

Make it simpler

      <input type="text" maxlength="3" />

and use an alert to show that max chars have been used.

查看更多
像晚风撩人
5楼-- · 2019-01-02 21:32

I alway do it like this:

$(document).ready(function(){
var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
    maxChars.bind('keyup', function(e){
        length = new Number(maxChars.val().length);
        counter = max_length-length;
        $("#sessionNum_counter").text(counter);
    });
}
});

Input:

<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>
查看更多
春风洒进眼中
6楼-- · 2019-01-02 21:32

Maxlength

The maximum number of characters that will be accepted as input. The maxlength attribute specifies the maximum number of characters allowed in the element.

Maxlength W3 schools

  <form action="/action_page.php">
     Username: <input type="text" name="usrname" maxlength="5"><br>
     <input type="submit" value="Submit">
   </form>
查看更多
公子世无双
7楼-- · 2019-01-02 21:35

You can use <input type = "text" maxlength="9"> or

<input type = "number" maxlength="9"> for numbers or <input type = "email" maxlength="9"> for email validation will show up

查看更多
登录 后发表回答