437

For <input type="number"> element, maxlength is not working. How can I restrict the maxlength for that number element?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Prasad
  • 58,881
  • 64
  • 151
  • 199

31 Answers31

409

And you can add a max attribute that will specify the highest possible number that you may insert

<input type="number" max="999" />

if you add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />

The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:

enter image description here

Community
  • 1
  • 1
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
  • 4
    Krister, this worked. Also as @Andy said i have used the oninput to slice the additional numbers. Reference http://mathiasbynens.be/notes/oninput – Prasad Dec 02 '11 at 11:41
  • 97
    This is correct, but should be noted as Andy states that this does not restrict one from typing a longer number. So it's not really the equivalent of maxlength in a text field. – DA. Mar 20 '12 at 23:14
  • 3
    DA : sure, but you could use `min="-999" max="999"` to fake `maxlength="3"`. – Quentin S. Aug 01 '14 at 13:50
  • 11
    If you simply entered a higher precision float, this will break. E.g. 3.1415926 gets around this because it is less than 999 and greater than 1. – kingsfoil Oct 08 '14 at 21:58
  • 79
    I don't know why this is so upvoted and accepted when it simply doesn't work! It only affects the "spinner" controls, and does nothing to stop the user typing a long number in. – Codemonkey Jul 31 '15 at 11:15
  • 2
    @Codemonkey - Even if a user is able to manually enter a value that is greater than `max` or lower than `min` the form will not be submitted. Instead you will get a popup that tells you to enter a value inside the specified range. – Cyclonecode Jul 31 '15 at 11:56
  • 2
    Hardly a good user experience compared to a JS maxlength simulator though – Codemonkey Aug 01 '15 at 12:24
  • 1
    @alex0112 not sure why no one's responded to your comment. As of 09/28/2015, in Chrome at least, `3.1415926` does not break this at all. The popup will say `Please enter a valid value. Closest numbers are 3 and 4`. So.. please delete your comment so as not to confuse others – Don Cheadle Sep 28 '15 at 22:02
  • 1
    *"upon submitting the form"* - But if the form is not sumitted normally (e.g., if submitted via Ajax, or if the values are used in JS calculations prior to submit) then the field can hold an invalid value so you still need JS validation. I can't think of any reasons why `maxlength` shouldn't work at the same time as `max` and `min`, but it just doesn't... – nnnnnn Aug 02 '16 at 00:43
  • 2
    @nnnnnn - Well the question in not tagged with either ajax or js? – Cyclonecode Aug 02 '16 at 14:28
  • @Cyclone Well I just ran into this exact issue and it was being submitted normally -- in chrome, but the input was no longer on screen because it was part of a multi-step dialog before the actual submit. – Robert McKee Oct 09 '16 at 23:26
  • 2
    On Angular 13 if you specify min as 0 and max as 10, user can still enter 11 and form submits normaly. It is simply not working. – Bogdan Onyshenko Feb 09 '22 at 13:38
128

You can specify the min and max attributes, which will allow input only within a specific range.

<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">

This only works for the spinner control buttons, however. Although the user may be able to type a number greater than the allowed max, the form will not submit.

Chrome's validation message for numbers greater than the max
Screenshot taken from Chrome 15

You can use the HTML5 oninput event in JavaScript to limit the number of characters:

myInput.oninput = function () {
    if (this.value.length > 4) {
        this.value = this.value.slice(0,4); 
    }
}
Jackson
  • 9,188
  • 6
  • 52
  • 77
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 14
    One possible issue with that JavaScript approach: It might not work as expected if the insertion point isn't at the end of the value. For example, if you enter the value "1234" in the input field, then move the insertion point back to the beginning of the value and type "5", you end up with the value "5123". This is different than an input type="text" field with a maxlength of 4, where the browser won't let you type a 5th character into the "full" field, and the value would remain "1234". – Jon Schneider Aug 09 '13 at 13:08
  • @Andy, Obviously the question is looking for a non-JS way to do `maxlength`............. – Pacerier Jan 26 '15 at 13:29
  • 5
    @Pacerier: did something in my answer imply that I thought otherwise? As you can see, I offered the closest possible solution that can be achieved using only HTML, along with an additional suggestion that uses JavaScript where the OP might have wanted to prevent the user typing more characters than permitted. – Andy E Jan 26 '15 at 16:43
92

If you are looking for a Mobile Web solution in which you wish your user to see a number pad rather than a full text keyboard. Use type="tel". It will work with maxlength which saves you from creating extra javascript.

Max and Min will still allow the user to Type in numbers in excess of max and min, which is not optimal.

Duane
  • 4,460
  • 1
  • 25
  • 27
  • 10
    I've found that this isn't the best solution for numeric input because a "tel" input allows for additional symbols, and it displays letters beside each number. The purely numeric keyboard looks much cleaner. – hawkharris Jul 25 '14 at 18:31
  • @hawkharris You are correct, type="number" is the cleaner UI. It is easier to accidentally type in a bad char. So additional validation is needed to ensure the user doesn't enter bad data. But also consider that the user could just as easily enter all decimal points as well with a number keyboard. Also it does not solve the question above without additional JavaScript. – Duane Jul 25 '14 at 19:51
  • 2
    if used with pattern="[0-9]*" the extra symbols will be disabled – apereira Sep 18 '18 at 15:33
  • But the tel type will be read a such by assistive technologies, letting think the user needs to enter a phone number. This is worse than using the default text type... – Capsule Feb 18 '19 at 04:17
  • 1
    This is one of the best summaries of user-friendly numeric input modes: https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode/ To save you a click, this HTML covers a lot of ground, and supports lots of browsers: `````` Then you can enhance this with some JavaScript if you need – spjpgrd Jun 20 '19 at 16:15
  • @spjpgrd: Good find, but `type` should be `text` and not `number`, as per article that you linked to: `` – user1438038 Dec 03 '21 at 17:01
  • @user1438038 — ah, you're right. I'd edit it, but I think it's been too long since I wrote that. – spjpgrd Jan 09 '23 at 22:39
89

You can combine all of these like this:

<input name="myinput_drs"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "3"
min = "1"
max = "999" />

<script>
  // This is an old version, for a more recent version look at
  // https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
  function maxLengthCheck(object)
  {
    if (object.value.length > object.maxLength)
      object.value = object.value.slice(0, object.maxLength)
  }
</script>


Update:
You might also want to prevent any non-numeric characters to be entered, because object.length would be an empty string for the number inputs, and therefore its length would be 0. Thus the maxLengthCheck function won't work.

Solution:
See this or this for examples.

Demo - See the full version of the code here:
http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

Update 2: Here's the update code: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/

Update 3: Please note that allowing more than a decimal point to be entered can mess up with the numeral value.

Community
  • 1
  • 1
David Refoua
  • 3,476
  • 3
  • 31
  • 55
  • This is a good solution, but I find that object.value.length returns 0 if there are any non-numeric values entered. – Andrew Dec 14 '14 at 21:47
  • 1
    @AndrewSpear That's because object.value would be an empty string if you enter non-numeric values in inputs with a type of 'number' set. See the documentation. Also, please read my update in order to fix this problem. – David Refoua Dec 17 '14 at 01:08
  • 1
    This still breaks if you input more than one decimal point, like 111..1111. Don't use this code for security, as malicious code may still get passed through. – PieBie Dec 21 '15 at 13:52
  • @PieBie Dude, this code is for 3+ years ago. Use jQuery instead. – David Refoua Dec 21 '15 at 18:38
  • 2
    yeah, I know that, but beginners might still just copy-paste it. – PieBie Dec 22 '15 at 07:45
37

Or if your max value is for example 99 and minimum 0, you can add this to input element (your value will be rewrited by your max value etc.)

<input type="number" min="0" max="99" 
   onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">

Then (if you want), you could check if is input really number

Richard
  • 371
  • 3
  • 3
32

it's very simple, with some javascript you can simulate a maxlength, check it out:

//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />
Brad Allred
  • 7,323
  • 1
  • 30
  • 49
Maycow Moura
  • 6,471
  • 2
  • 22
  • 19
25

Lets say you wanted the maximum allowed value to be 1000 - either typed or with the spinner.

You restrict the spinner values using: type="number" min="0" max="1000"

and restrict what is typed by the keyboard with javascript: onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }"

<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">
24

You can specify it as text, but add pettern, that match numbers only:

<input type="text" pattern="\d*" maxlength="2">

It works perfect and also on mobile ( tested on iOS 8 and Android ) pops out the number keyboard.

Chris Panayotoff
  • 1,744
  • 21
  • 24
  • The pattern attribute is not supported in IE9 and earlier versions, and it has partial support in Safari: http://caniuse.com/#feat=input-pattern – diazdeteran Oct 09 '15 at 03:02
  • Yes, thanks for pointing, but we dropped IE9 support ( cutting the mustard from it ), and I prefer it over JS methods. Depends on the project. – Chris Panayotoff Oct 09 '15 at 08:18
  • 5
    A user isn't prevented from entering non-numeric characters with this. They can enter 2 of any char. The `pattern` only causes validation highlighting. – brt Oct 04 '18 at 16:34
  • tested on Android 9 (Nokia 8) but i get the regular keyboard :( any ideas? – oriadam Mar 01 '20 at 09:55
  • This does not restrict input to numbers only. – Vincent Feb 17 '23 at 21:48
18

//For Angular I have attached following snippet.
<div ng-app="">
  <form>
    Enter number: <input type="number" ng-model="number" onKeyPress="if(this.value.length==7) return false;" min="0">
  </form>
  <h1>You entered: {{number}}</h1>
</div>

If you use "onkeypress" event then you will not get any user limitations as such while developing ( unit test it). And if you have requirement that do not allow user to enter after particular limit, take a look of this code and try once.

Prasad Shinde
  • 658
  • 1
  • 7
  • 14
  • 1
    The problems I see here are: 1. replace with select the text and type does not work if the input has reached 7 numbers 2. increasing the input by 1 when the overflow "boarder" hits does work --> 9999999 and klick the up button. Breaks the limitation – Edub Jun 01 '17 at 09:38
  • I tried with simple version javascript. If you want you can see using Run code snippet. As such I didnt find any limitation. – Prasad Shinde Jun 01 '17 at 12:08
  • 1
    Didn't find any limitations either. It stops at 7 digits. I'm using this solution for my code. – Claudio Sep 19 '17 at 22:39
  • There is a limitiation. When you hit the limit, select all and want to replace them it doesn't work. The replacement works for me only when I overwrite the value with the cur one before I return false. – Insomnia88 Nov 19 '19 at 13:56
  • @Insomnia88 ,@edub what if we write function and check necessary conditions... – Prasad Shinde Dec 24 '19 at 14:39
15

Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that. Assuming the user doesn't want to use a function inside every event related to the input. Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.

// Reusable Function to Enforce MaxLength
function enforce_maxlength(event) {
  var t = event.target;
  if (t.hasAttribute('maxlength')) {
    t.value = t.value.slice(0, t.getAttribute('maxlength'));
  }
}

// Global Listener for anything with an maxlength attribute.
// I put the listener on the body, put it on whatever.
document.body.addEventListener('input', enforce_maxlength);
label { margin: 10px; font-size: 16px; display: block }
input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }
span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }
<label for="test_input">Text Input</label>
<input id="test_input" type="text" maxlength="5"/>
<span>set to 5 maxlength</span>

<br>

<label for="test_input">Number Input</label>
<input id="test_input" type="number" min="0" max="99" maxlength="2"/>
<span>set to 2 maxlength, min 0 and max 99</span>
Buttars
  • 395
  • 3
  • 5
14

Simple solution which will work on,

  • Input scroll events

  • Copy paste via keyboard

  • Copy paste via mouse

  • Input type etc cases

    <input id="maxLengthCheck" 
           name="maxLengthCheck" 
           type="number" 
           step="1" 
           min="0" 
           oninput="this.value = this.value > 5 ? 5 : Math.abs(this.value)" />
    

See there is condition on this.value > 5, just update 5 with your max limit.

Explanation:

  • If our input number is more then our limit update input value this.value with proper number Math.abs(this.value)

  • Else just make it to your max limit which is again 5.

Bharat
  • 5,869
  • 4
  • 38
  • 58
13

Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code for simple implementation.

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />
Avinash Jain
  • 7,200
  • 2
  • 26
  • 40
10

As stated by others, min/max is not the same as maxlength because people could still enter a float that would be larger than the maximum string length that you intended. To truly emulate the maxlength attribute, you can do something like this in a pinch (this is equivalent to maxlength="16"):

<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">
thdoan
  • 18,421
  • 1
  • 62
  • 57
  • slice will delete characters without end user knowledge when inserted in-between. whereas max-length will block. – Pradeep Kumar Dec 26 '15 at 08:56
  • @PradeepKumarPrabaharan `maxlength` is not supported by number inputs. In my example, `value.slice(0,16)` won't kick in unless the input value is longer than 16 characters. – thdoan Dec 27 '15 at 12:44
  • yes maxlength is not supported for number inputs.. this code is gud but this code doesn't match the maxlength's property exactly.. – Pradeep Kumar Dec 28 '15 at 05:22
  • @TobiasGaertner `type="number"` takes care of that :). – thdoan Oct 21 '16 at 03:45
  • @10basetom ...depending to the browser... e.g. in FF you can still enter characters and they won't stop after the limit -- but related to the idea of the type number this is an acceptable solution. – Tobias Gaertner Oct 25 '16 at 11:51
7

I had this problem before and I solved it using a combination of html5 number type and jQuery.

<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>

script:

$("input[name='minutes']").on('keyup keypress blur change', function(e) {
    //return false if not 0-9
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       return false;
    }else{
        //limit length but allow backspace so that you can still delete the numbers.
        if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
            return false;
        }
    }
});

I don't know if the events are a bit overkill but it solved my problem. JSfiddle

kayz1
  • 7,260
  • 3
  • 53
  • 56
tiltdown
  • 451
  • 1
  • 11
  • 26
7

a simple way to set maxlength for number inputs is:

<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
HexboY
  • 471
  • 1
  • 5
  • 8
6

Maycow Moura's answer was a good start. However, his solution means that when you enter the second digit all editing of the field stops. So you cannot change values or delete any characters.

The following code stops at 2, but allows editing to continue;

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"
Tim Wright
  • 61
  • 1
  • 1
5

HTML Input

 <input class="minutesInput" type="number" min="10" max="120" value="" />

jQuery

 $(".minutesInput").on('keyup keypress blur change', function(e) {

    if($(this).val() > 120){
      $(this).val('120');
      return false;
    }

  });
Hector
  • 682
  • 3
  • 14
  • 27
5

Ugh. It's like someone gave up half way through implementing it and thought no one would notice.

For whatever reason, the answers above don't use the min and max attributes. This jQuery finishes it up:

    $('input[type="number"]').on('input change keyup paste', function () {
      if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value) || 0);
      if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
    });

It would probably also work as a named function "oninput" w/o jQuery if your one of those "jQuery-is-the-devil" types.

Ivan Castellanos
  • 8,041
  • 1
  • 47
  • 42
Michael Cole
  • 15,473
  • 7
  • 79
  • 96
5
    <input type="number" maxlength="6" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">

This worked for me with no issues

Code with Benji
  • 666
  • 9
  • 17
4

You can try this as well for numeric input with length restriction

<input type="tel" maxlength="3" />
shinobi
  • 2,511
  • 1
  • 19
  • 27
4

As with type="number", you specify a max instead of maxlength property, which is the maximum possible number possible. So with 4 digits, max should be 9999, 5 digits 99999 and so on.

Also if you want to make sure it is a positive number, you could set min="0", ensuring positive numbers.

Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
3
<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />

or if you want to be able enter nothing

<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />
j4r3k
  • 156
  • 5
2

As I found out you cannot use any of onkeydown, onkeypress or onkeyup events for a complete solution including mobile browsers. By the way onkeypress is deprecated and not present anymore in chrome/opera for android (see: UI Events W3C Working Draft, 04 August 2016).

I figured out a solution using the oninput event only. You may have to do additional number checking as required such as negative/positive sign or decimal and thousand separators and the like but as a start the following should suffice:

function checkMaxLength(event) {
 // Prepare to restore the previous value.
 if (this.oldValue === undefined) {
  this.oldValue = this.defaultValue;
 }

 if (this.value.length > this.maxLength) {
  // Set back to the previous value.
  this.value = oldVal;
 }
 else {
  // Store the previous value.
  this.oldValue = this.value;
  
  // Make additional checks for +/- or ./, etc.
  // Also consider to combine 'maxlength'
  // with 'min' and 'max' to prevent wrong submits.
 }
}

I would also recommend to combine maxlength with min and max to prevent wrong submits as stated above several times.

markus s
  • 1,024
  • 1
  • 11
  • 20
1

Since I was look to validate and only allow integers I took one the existing answers and improve it

The idea is to validate from 1 to 12, if the input is lower than 1 it will be set to 1, if the input is higher than 12 it will be set to 12. Decimal simbols are not allowed.

<input id="horaReserva" type="number" min="1" max="12" onkeypress="return isIntegerInput(event)" oninput="maxLengthCheck(this)">
function maxLengthCheck(object) {
    if (object.value.trim() == "") {

    }
    else if (parseInt(object.value) > parseInt(object.max)) {
        object.value = object.max ;
    }
    else if (parseInt(object.value) < parseInt(object.min)) {
        object.value = object.min ;
    }
}

function isIntegerInput (evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode (key);
    var regex = /[0-9]/;
    if ( !regex.test(key) ) {
        theEvent.returnValue = false;

        if(theEvent.preventDefault) {
            theEvent.preventDefault();
        }
    }
}
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
0

I know there's an answer already, but if you want your input to behave exactly like the maxlength attribute or as close as you can, use the following code:

(function($) {
 methods = {
    /*
     * addMax will take the applied element and add a javascript behavior
     * that will set the max length
     */
    addMax: function() {
        // set variables
        var
            maxlAttr = $(this).attr("maxlength"),
            maxAttR = $(this).attr("max"),
            x = 0,
            max = "";

        // If the element has maxlength apply the code.
        if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {

            // create a max equivelant
            if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
                while (x < maxlAttr) {
                    max += "9";
                    x++;
                }
              maxAttR = max;
            }

            // Permissible Keys that can be used while the input has reached maxlength
            var keys = [
                8, // backspace
                9, // tab
                13, // enter
                46, // delete
                37, 39, 38, 40 // arrow keys<^>v
            ]

            // Apply changes to element
            $(this)
                .attr("max", maxAttR) //add existing max or new max
                .keydown(function(event) {
                    // restrict key press on length reached unless key being used is in keys array or there is highlighted text
                    if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
                });;
        }
    },
    /*
     * isTextSelected returns true if there is a selection on the page. 
     * This is so that if the user selects text and then presses a number
     * it will behave as normal by replacing the selection with the value
     * of the key pressed.
     */
    isTextSelected: function() {
       // set text variable
        text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return (text.length > 0);
    }
};

$.maxlengthNumber = function(){
     // Get all number inputs that have maxlength
     methods.addMax.call($("input[type=number]"));
 }

})($)

// Apply it:
$.maxlengthNumber();
Philll_t
  • 4,267
  • 5
  • 45
  • 59
  • @Phill_t maybe you can enlighten me? I used your code and it is working well in principal BUT "$(this).attr("maxlength")" always delivers 2. AND why would it be better to use "$(this).attr("maxlength")" if it was working instead of just "this.maxlength" which I tested and was working as expected and is shorter and imho also clearer to read? Did I miss anything? – markus s Jan 26 '17 at 06:22
  • What do you mean "delivers 2"? – Philll_t Jan 26 '17 at 06:40
  • Phill_t my apologies. "this.maxLength" is only working in the scope of the keydown function. In the function "addMax" "this" is the document rather than the expected element and therefore has different attribute values. How would I get access to the number input instead? Is the above code really working on your side? I tested with Chrome/Opera/Vivaldi, Firefox, Edge, IE and Safari and had the same results for each browser. Okay, in Edge maxlegth="1" and maxlength="2" where indeed working but "$(this).attr("maxlength")" don't increase further for any higher number!!? @anybody: Any suggestions? – markus s Jan 26 '17 at 07:01
  • As I said it always is two because it is called on the document rather than on the element in question as I found out when I was debugging it. By the way you may also want to look at my solution which I figured out after studying yours: http://stackoverflow.com/a/41871960/1312012 – markus s Jan 26 '17 at 11:01
0

I use a simple solution for all inputs (with jQuery):

$(document).on('input', ':input[type="number"][maxlength]', function () {
    if (this.value.length > this.maxLength) {
        this.value = this.value.slice(0, this.maxLength); 
    }
});

The code select all input type="number" element where maxlength has defined.

CsZsombor
  • 69
  • 1
  • 4
0

If anyone is struggling with this in React the easiest solution that i found to this is using the onChange function like this:

    const [amount, setAmount] = useState("");
    
   return(
    <input onChange={(e) => {
    setAmount(e.target.value);
    if (e.target.value.length > 4) {
         setAmount(e.target.value.slice(0, 4));
    }
    }} value={amount}/>)

So what this basically does is it takes the value of the input and if the input value length is bigger than 4 it slices all the numbers after it so you only get the first 4 numbers (of course you can change the amount of numbers you can type by changing all 4's in the code). I hope this helps to anyone who is struggling with this issue. Also if you wanna learn what the slice method does you can check it out here

Dremiq
  • 335
  • 3
  • 10
0

Non-optimal solutions

  • Rellying on min and max

    As some people have pointed out, you can use max and min attributes to set the range of allowed values, but this won't prevent the user from typing longer text like maxlength attribute does.

  • keydown, keyup and other non-input event listeners

    It is important to say that not all users work with a desktop keyboard so keydown or keyup events are not the best approch to accomplish this for all kind of input methods such as mobile keyboards

  • slice, substring and other String methods

    This methods work well only if the user is typing at the end of the input, but if it is typing anywhere else, the character input won't be prevented. It will be added and the last character of the input will be removed instead

Solution for all situations

If you really want to prevent the character from being added to the input, when the desired length is reached (or any other condition is met), you can handle it using the beforeinput event listener which is supported for all major browsers: https://caniuse.com/?search=beforeinput.

It is called just before the input event listener which means the input value hasn't changed already, so you can store it an set to the input after.

const input = document.querySelector("input");

input.addEventListener("beforeinput", () => {
  const valueBeforeInput = event.target.value;
  event.target.addEventListener("input", () => {
    if (event.target.value.length > 10) {
      event.target.value = valueBeforeInput;
    }
  }, {once: true});
});
<input type=number />

If you want to support browsers before 2017 (2020 and 2021 for Edge and Firefox respectively) don't use the beforeinput event listener and use the code below instead.

const input = document.querySelector("input");

let valueBeforeInput = input.value;
input.addEventListener("input", () => {
    if (event.target.value.length > 10) {
        event.target.value = valueBeforeInput;
    }
    valueBeforeInput = event.target.value;
});
<input type=number />
Bernat
  • 825
  • 1
  • 6
  • 10
0

More relevant attributes to use would be min and max.

Marcel
  • 27,922
  • 9
  • 70
  • 85
-1

This might help someone.

With a little of javascript you can search for all datetime-local inputs, search if the year the user is trying to input, greater that 100 years in the future:

$('input[type=datetime-local]').each(function( index ) {

    $(this).change(function() {
      var today = new Date();
      var date = new Date(this.value);
      var yearFuture = new Date();
      yearFuture.setFullYear(yearFuture.getFullYear()+100);

      if(date.getFullYear() > yearFuture.getFullYear()) {

        this.value = today.getFullYear() + this.value.slice(4);
      }
    })
  });
Simon Berton
  • 468
  • 5
  • 13
-1

Here's the simplest solution to use the maxlength:

<form>
   <input class="form-control" id="code_pin" oninput="if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" maxlength="4">
</form>
Félix Maroy
  • 1,389
  • 2
  • 16
  • 21