134

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?

random
  • 9,774
  • 10
  • 66
  • 83
BruceyBandit
  • 3,978
  • 19
  • 72
  • 144

14 Answers14

193

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.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • I found this answer useful when limiting in the inputting phase. You can also limit it in the validation phase when submitting and pop up a validation message using the `pattern` attribute. See http://stackoverflow.com/questions/10281962/is-there-a-minlength-validation-attribute-in-html5 –  Nov 03 '16 at 16:01
34

The simplest way to do so:

maxlength="5"

So.. Adding this attribute to your control:

<input type="text" 
    id="sessionNo" 
    name="sessionNum" 
    onkeypress="return isNumberKey(event)" 
    maxlength="5" />
Nonym
  • 6,199
  • 1
  • 25
  • 21
10

Make it simpler

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

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

3rdthemagical
  • 5,271
  • 18
  • 36
user5829707
  • 101
  • 1
  • 4
10

Add the following to the header:

<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
</script>

    <input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);" 
onKeyUp="limitText(this,5);"" />
b3labs
  • 960
  • 1
  • 14
  • 29
  • `this.form.sessionNo` seems a little suspect. Why not just `this`? Also, `limitCount` and `limitNum` also seem out of order/unnecessary? – Jared Farrish Dec 17 '11 at 14:30
  • 1
    Corrected it. Doing this way if you wanted to limit it to certain characters or numbers you could, but if you don't care about that then max Length would work fine. So say if you wanted the values to be between 1-50 you could or all positive numbers, etc. – b3labs Dec 17 '11 at 14:34
  • `this.form.sessionNo` still doesn't seem right. `this` in that context will point to the `input`, not `document`. – Jared Farrish Dec 17 '11 at 14:35
  • Still not right, it doesn't reference the `form` either. `this` is all you need. Also, technically if you were wanting to reference the element by the `form`, it would be by (`form`/`input`) `name`, not `id`, ie: `document.formName.sessionNum`. – Jared Farrish Dec 17 '11 at 14:37
  • Correct I typed to fast it was wrapped in the a form before. But you'd just pass the ref to the input into the function to get the current value of the field then add any logic you want to limit that field. – b3labs Dec 17 '11 at 14:42
  • This did it just what I was looking for. Cheers! – Eshwar Sep 21 '16 at 17:17
8

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

Mahdi Jazini
  • 791
  • 9
  • 16
  • 1
    @lopezdp, there are multiple ways to "get around" html/javascript restrictions. The easiest to check is to open your page with Chrome, "inspect element" and manually modify HTML. The more elaborate way to get around - write a script that will post the data ignoring any restrictions (using curl library or something similar). As a backend developer you should never trust frontend validation of data - all the rules should be duplicated on server. Frontend validation is just a way to save time for the user by pointing at obvious errors without making a request to the server. – Val Petruchek Aug 12 '17 at 05:54
6
<input type="text" maxlength="5">

the maximum amount of letters that can be in the input is 5.

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
anonymous
  • 77
  • 1
  • 1
3

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>
3rdthemagical
  • 5,271
  • 18
  • 36
Kondal
  • 2,870
  • 5
  • 26
  • 40
2

I always do it like this:

$(document).ready(function() {
    var maxChars = $("#sessionNum");
    var max_length = maxChars.attr('maxlength');
    if (max_length > 0) {
        maxChars.on('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>
Nice18
  • 476
  • 2
  • 12
Sašo Krajnc
  • 133
  • 2
  • 3
  • 11
1

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

1
<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">

function maxLengthCheck(object) {
  if (object.value.length > object.maxLength)
  object.value = object.value.slice(0, object.maxLength)
}
P.Banerjee
  • 189
  • 2
  • 14
0

The following code includes a counted...

var count = 1;

do {
    function count_down(obj, count){

    let element = document.getElementById('count'+ count);

    element.innerHTML = 80 - obj.value.length;

    if(80 - obj.value.length < 5){
        element.style.color = "firebrick";
    }else{
        element.style.color = "#333";
    }
}
count++;
} while (count < 20); 
.text-input {
    padding: 8px 16px;
    width: 50%;
    margin-bottom: 5px;
    margin-top: 10px;
    font-size: 20px;
    font-weight: 700;
    font-family: Raleway;
    border: 1px solid dodgerblue;
  }
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80"  class="text-input" name="bikeTitle" ></p>
        <span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
0

Late to the party, but if you want a full proof way to restrict numbers or letters that is simply javascript and also limits length of characters:

Change the second number after .slice to set the how many characters. This has worked much better for me then maxlength.

Just Numbers:

oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);

Just Letters:

oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'').slice(0,20);"

Full example:

<input type="text" name="MobileNumber" id="MobileNumber" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);"/>
eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20
-1

Use maxlenght="number of charcters"

<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />
Rahul Jain
  • 390
  • 6
  • 20
-1
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);"  placeholder="MobileNumber">

<script>
function checkNumber(key) {
  console.log(key);
  var inputNumber = document.querySelector("#MobileNumber").value;
  if(key.key >= 0 && key.key <= 9) {
    inputNumber += key.key;
  }
  else {
    key.preventDefault();
  }
}
</script>
Yash Patel
  • 11
  • 1
  • 3