425

The maxlength attribute is not working with <input type="number">. This happens only in Chrome.

<input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>
André Dion
  • 21,269
  • 7
  • 56
  • 60
Prajila V P
  • 5,027
  • 2
  • 23
  • 36

34 Answers34

481

From MDN's documentation for <input>

If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.

So maxlength is ignored on <input type="number"> by design.

Depending on your needs, you can use the min and max attributes as inon suggested in his/her answer (NB: this will only define a constrained range, not the actual character length of the value, though -9999 to 9999 will cover all 0-4 digit numbers), or you can use a regular text input and enforce validation on the field with the new pattern attribute:

<input type="text" pattern="\d*" maxlength="4">
André Dion
  • 21,269
  • 7
  • 56
  • 60
  • but my input type is number and all other browsers support this function – Prajila V P Aug 29 '13 at 12:24
  • 23
    Also note that `type="number"` is a new type from the HTML 5 specification. If the browser you're testing in doesn't recognize `type="number"` it will treat it as `type="text"` which *does* respect the `maxlength` attribute. This may explain the behaviour you're seeing. – André Dion Aug 29 '13 at 12:31
  • I think using min/max as per the other answer is a better solution - the input[type=number] element is the most semantically-correct. Changing a text input to having a numeric regexp seems like a slightly hacky workaround, when using input[type=number] with min/max solves this properly. – fooquency Feb 11 '14 at 14:36
  • 16
    @fooquency, you are not right here, as you actually can't restrict physical length of "keyboard input" into `type=number` input by setting `max` attribute. This attribute only restricts number chosen by input's spinner. – Kamilius Feb 19 '15 at 07:44
  • 7
    what is `\d*` here ? – Pardeep Jain Feb 29 '16 at 10:04
  • 2
    @PardeepJain `\d*` is a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) that matches 0 or more digit characters. – André Dion Feb 29 '16 at 18:45
  • 6
    pattern="\d*" does not work in IE11 or Firefox 56. https://jsfiddle.net/yyvrz84v/ – Reado Oct 20 '17 at 08:21
  • 3
    Pattern behaves the same way as max/min on a number input, in that you can enter text that violates the pattern, but the input won't block the text. It only prevents you from submitting a field with an input value that violates the condition – apoteet Nov 30 '17 at 23:36
  • 11
    Using `regex` and pattern is a incredibly creative. But in mobile, no different `Android` or `iOS`, it's a `text` input so it cause a bad `UX`. – AmerllicA Jul 21 '18 at 08:17
  • 1
    yeah, what @AngelHotxxx said... not a solution to use pattern on mobile (if you want to have phone numbers for example) – DS_web_developer Oct 26 '18 at 09:59
  • 1
    not working on desktop. so its not an appropriate solution – Sam Feb 15 '20 at 11:31
  • 2
    But, it allows alphabetic characters. How do I avoid it? – Dman Cannon Jan 12 '21 at 11:00
  • 2
    @DmanCannon, `pattern` only enforces validation. It doesn't limit input. – André Dion Jan 12 '21 at 13:45
  • Note that `pattern` does not work with input `type="number"` – Ali Baghban Mar 29 '22 at 11:00
  • this doesn't stop the user from entering a non-numeric value. it only warns the user if you're submitting a form. i think an input handler is what op needs – Wassim Katbey Nov 29 '22 at 19:35
375

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.

<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
  • @Guedes version works for me in all tested devices setting type to "number". However I don't fully understand the second part of the expression `||0/1` – Barleby Nov 24 '16 at 09:11
  • 87
    @Barleby. Just `oninput="this.value=this.value.slice(0,this.maxLength)"` should work – Washington Guedes Nov 24 '16 at 11:11
  • In my case this solution doesn´t work properly on Firefox, but on Google Chrome works perfectly. Do you have idea how to fix this issue? type="number" is problem on Firefox because field shows little boxes inside - Please see screenshot - http://prntscr.com/dgry8x – Mile Mijatović Dec 08 '16 at 07:48
  • Which version of firefox you are using... I have tested and its working perfectly – Avinash Jain Dec 09 '16 at 09:05
  • 3
    @WashingtonGuedes’s code above worked for me on `` http://stackoverflow.com/questions/18510845/maxlength-ignored-for-input-type-number-in-chrome#comment68792329_34641129 – David Yeiser Mar 01 '17 at 18:20
  • I have made a simple drop in javascript that you can add to you main js file that will simply look for number input and if it has a maxlength attribute it will restrict to this much like how maxlength should work `$('input[type="number"]').on('input', function() { var attr = $(this).attr('maxlength'); if (typeof attr !== typeof undefined && attr !== false) { if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength) } });` – Phil Cook Apr 17 '18 at 11:38
  • Why does `this.maxLength` need to be camel cased? Using `this.maxlength`, `this.maxlEngth` or any other variation doesn't seem to work, why does the chosen wording work? – JCKE Sep 17 '18 at 17:49
  • 1
    Beware that leading zeros are not displayed with this approach! – Ali Celebi Nov 11 '19 at 08:28
  • 3
    Technically, the `maxlength` attribute for `number` type is invalid HTML5, so it would be possible the `.maxLength` property will be dropped from Javascript. I think it's would better to use a `data` attribute: `` – Tim Dec 27 '19 at 20:25
  • This solution is great, it really helped me, thanks, Neha Jain. But it still allows to input the following characters when the max length is already reached: **Plus Sign (+)**, **Minus Sign (-)**, **Full Stop Character (.)**, and **Exponent Characters (e, E)**. This limitation should be able to be removed by disallowing these characters' input just in that oninput event handler. – Ray Chen Dec 21 '20 at 03:12
  • This approach doesn't work as slice() function does not work with input type=number in some ts versions – Murtaza Bharmal Jul 28 '21 at 06:31
  • OMG @WashingtonGuedes this is a f*ck nice trick solution for this problem, thanks you and Neha Jain – Edson Filho Aug 04 '22 at 20:18
114

Many guys posted onKeyDown() event which is not working at all i.e. you can not delete once you reach the limit. So instead of onKeyDown() use onKeyPress() and it works perfectly fine.

Below is working code:

User will not be allowed to enter more than 4 digits
<br>
<input type="number" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==4) return false;" />
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
  • 4
    this is very helpful, a shorter and much better than any other answers here while keeping the html5 _`number`_ input type – Dexter Bengil Sep 30 '18 at 13:50
  • if user enters 4 digits and later wants to update any of the digit that won't be possible, because after 4 digits are entered, it won't allow anything in the textbox, not even update. – Abbas Feb 22 '19 at 06:11
  • @Abbas the statement you made is not true. It is possible to update later even after you entered 4 digits. **Run code snippet** and see the results. – Vikasdeep Singh Feb 22 '19 at 06:27
  • 4
    I tried, after entering 4 digits, the textbox, simply gets frozen with no room for any updates, neither delete nor backspace keys works, nothing works, how to edit any digits, please mention. – Abbas Feb 23 '19 at 09:02
  • 2
    I was able to enter in ur snippet (1.2.3.4.5.5.6.76.7) – Alaa' May 15 '19 at 12:24
  • 1
    This should be the accepted answer. Very clever way to keep number field. Just be sure to add a min/max attribute as the spin buttons can still go above the 4 digits if they are used – NiallMitch14 Sep 25 '19 at 14:10
  • 4
    Not works when you type 9999 and press the up button on input. – Csaba Gergely Oct 07 '19 at 11:47
  • That **pattern** attribute setting in the above code should be not working. Per the https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Pattern_validation here, elements do not support use of the **pattern** attribute. And the user still can input numbers more than 4 digits here using copying and pasting (e.g., I can paste the number 12345 using Ctrl+V or the Paste item in the context menu), since the **onkeypress** attribute only handle the keyboard event, I think the **oninput** attribute should be used here. – Ray Chen Dec 21 '20 at 04:46
  • 1
    The **Exponent Characters (e, E)** are still able to be inputted, which may be not expected most of the time. – Ray Chen Dec 21 '20 at 04:55
  • This solution does not prevent pasting more than 4 digits – FS'Wæhre Jun 14 '21 at 10:56
  • what if user copy some number more then 4 digit and paste in textbox ?? it will not handle this case – Ali Sep 14 '21 at 11:38
  • The `keypress` event is deprecated: [keypress_event](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event). Don't use it. – undrivendev Feb 08 '22 at 11:26
  • I might take it a bit further and make sure you always get the appropriate length `if (this.value.length == this.maxLength) return false;`. – Grandizer Mar 29 '22 at 12:42
58

I have two ways for you do that

First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:

<input type="tel" />

Second: Use a little bit of JavaScript:

<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />
Maycow Moura
  • 6,471
  • 2
  • 22
  • 19
  • 4
    your second answer isn't very good: if you reached 2 chars, you cannot delete any number. – vtni Nov 17 '14 at 18:36
  • Yes, I also noticed a Number input doesn't return value.length, anyway, I edited it including Backspace keycode – Maycow Moura Nov 19 '14 at 17:40
  • 2
    the array keys and delete (forward) button should be also include. – vtni Nov 20 '14 at 19:12
  • This is nice one . and this only working for me..upvoted – saleem ahmed Jan 15 '16 at 08:47
  • 1
    Great answer, tnx. However, I don't get the reason to use 'tel' instead of 'number' in this case. Moreover you can replace your condition of "event.keyCode!=8" with "event.keyCode>47 && event.keyCode < 58" in a case of natural numebrs to disable the user only from entering digits. – Dudi Apr 27 '17 at 21:36
  • type="number" onKeyDown="if(this.value.length>=12 && event.keyCode!=8) return false;" – nobjta_9x_tq Dec 02 '17 at 19:12
  • type"tel" can duplicate Dot[.] – Roshan Perera Jun 21 '21 at 07:26
  • Using "tel" to compensate for HTML's surprising failure to support "maxlength" for "number" types is very slick. – Joe Sep 21 '22 at 05:09
31

You can use the min and max attributes.

The following code do the same:

<input type="number" min="-999" max="9999"/>
Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50
inon
  • 1,689
  • 1
  • 19
  • 34
25

This works in Android as well

Change your input type to text and use "oninput" event to call function:

<input type="text" oninput="numberOnly(this.id);" maxlength="4" id="flight_number" name="number"/>

Now use Javascript Regex to filter user input and limit it to numbers only:

function numberOnly(id) {
    // Get element by id which passed as parameter within HTML element event
    var element = document.getElementById(id);
    // This removes any other character but numbers as entered by user
    element.value = element.value.replace(/[^0-9]/gi, "");
}

Demo: https://codepen.io/aslami/pen/GdPvRY

Masood
  • 1,545
  • 1
  • 19
  • 30
  • 1
    best "numbers only" answer i've found. Others using evt.keycode seem to fail on my android – deebs Oct 01 '18 at 13:51
  • 1
    One very minor mod, change "this.id" to "this", numberOnly(id) to numberOnly(element), then you don't need the first line of numberOnly and it works without an id – tony Aug 20 '19 at 08:28
  • This is the simple way i found. This is my React code : `{AreaRef.current.value = e.target.value.replace(/[^0-9]/gi, "")}} />` – MustafaT Nov 30 '21 at 12:37
  • `oninput="this.value = this.value.replace(/[^0-9]/gi, '')"` works fine if it's a one-off. – jstafford Feb 21 '22 at 00:18
22

For React users,

Just replace 10 with your max length requirement

 <input type="number" onInput={(e) => e.target.value = e.target.value.slice(0, 10)}/>
mcnk
  • 1,690
  • 3
  • 20
  • 29
15

how to limit input type max length

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />
Peter
  • 1,124
  • 14
  • 17
10

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

<input type="tel" maxlength="4" />
shinobi
  • 2,511
  • 1
  • 19
  • 27
  • 11
    in some browsers (specifically mobile), the `tel` input will be automatically validated as such and in some weird cases leading `0`s will be changed to `1`s. – Philll_t Mar 19 '15 at 19:09
  • Another issue with this dirty solution imo is the browser's autocomplete being triggered. If you do specify tel as an input type (I wouldn't) add an autocomplete="off" tag – DeZeA Apr 15 '21 at 07:58
10

I once got into the same problem and found this solution with respect to my needs. It may help Some one.

<input type="number" placeholder="Enter 4 Digits" max="9999" min="0" 
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>

Happy Coding :)

Mohammad Mahroz
  • 432
  • 4
  • 14
8

try use tel :

 maxlength="5" type="tel"
aris
  • 409
  • 6
  • 8
8

I wrote a small and clean workaround. Using this function will make it work, as it should

  const inputHandler = (e) => {
    const { value, maxLength } = e.target;
    if (String(value).length >= maxLength) {
      e.preventDefault();
      return;
    }
  };

For example, it can be used in React like this:

<input
  type="number"
  maxlength="4"
  onKeyPress={inputHandler}
/>
ofarukcaki
  • 111
  • 3
  • 13
  • One thing to note about this solution is that, when the input is of maximum length, selecting all and pressing any key will not replace the input; you can only press backspace. The `return` is also redundant, assuming that there's no other code after the if statement. – encryptedcurse Feb 08 '22 at 00:30
7

Input type text and oninput event with regex to accept only numbers worked for me.

<input type="text" maxlength="4" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>
Jonathan Akwetey Okine
  • 1,295
  • 2
  • 15
  • 18
  • This is the best answer, it does not pass `maxLength` nor a static length in the javascript code. – TiyebM Oct 25 '22 at 13:41
6

Chrome (technically, Blink) will not implement maxlength for <input type="number">.

The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.

pwnall
  • 6,634
  • 2
  • 23
  • 30
6

Here is my solution with jQuery... You have to add maxlength to your input type=number

$('body').on('keypress', 'input[type=number][maxlength]', function(event){
    var key = event.keyCode || event.charCode;
    var charcodestring = String.fromCharCode(event.which);
    var txtVal = $(this).val();
    var maxlength = $(this).attr('maxlength');
    var regex = new RegExp('^[0-9]+$');
    // 8 = backspace 46 = Del 13 = Enter 39 = Left 37 = right Tab = 9
    if( key == 8 || key == 46 || key == 13 || key == 37 || key == 39 || key == 9 ){
        return true;
    }
    // maxlength allready reached
    if(txtVal.length==maxlength){
        event.preventDefault();
        return false;
    }
    // pressed key have to be a number
    if( !regex.test(charcodestring) ){
        event.preventDefault();
        return false;
    }
    return true;
});

And handle copy and paste:

$('body').on('paste', 'input[type=number][maxlength]', function(event) {
    //catch copy and paste
    var ref = $(this);
    var regex = new RegExp('^[0-9]+$');
    var maxlength = ref.attr('maxlength');
    var clipboardData = event.originalEvent.clipboardData.getData('text');
    var txtVal = ref.val();//current value
    var filteredString = '';
    var combined_input = txtVal + clipboardData;//dont forget old data

    for (var i = 0; i < combined_input.length; i++) {
        if( filteredString.length < maxlength ){
            if( regex.test(combined_input[i]) ){
                filteredString += combined_input[i];
            }
        }
    }
    setTimeout(function(){
        ref.val('').val(filteredString)
    },100);
});

I hope it helps somebody.

zhu man
  • 3
  • 2
harley81
  • 190
  • 2
  • 12
  • I had the same idea (though I used the "input" event), but I think the solution that @WashingtonGuedes wrote in a comment to another answer is much simpler: `this.value = this.value.slice(0, this.maxLength);` Do you think this has any issue? I haven't found any so far. It covers pasted text too. – nonzaprej Jul 24 '19 at 10:39
  • I like the long way. The Usage of RegExp is very flexible. – harley81 Aug 23 '19 at 12:40
6
<input type="number" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">

DEMO - JSFIDDLE

Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25
6

The below code will allow the user to:

  1. Enter digits only in the 0-999 range.
  2. This also restricts the user not to enter more than 3 characters.
  3. When the user enters more than 3 characters then it will clear the textbox.
<input type="number" name="test_name" min="0" max="999" oninput="validity.valid||(value='');"> 
J_K
  • 93
  • 1
  • 7
6

this code worked for me

<form method="post">
      <label for="myNumber">My Number:</label>
      <input type="number" maxlength="9" required
      oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" >
     <br><br>
      <input type="submit" value="Submit">
</form>
Akbarali
  • 688
  • 7
  • 16
5

Try this,

<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
5

If you want to do it in a React Function Component or without using "this", here is a way to do it.

<input onInput={handleOnInput}/>

const handleOnInput = (e) => {
  let maxNum = 4;
  if (e.target.value.length > maxNum) {
    e.target.value = e.target.value.slice(0, maxNum);
  }
};
Dremiq
  • 335
  • 3
  • 10
  • 1
    Thanks, this worked for me. Plus I updated this: `let maxNum = 4;` To `let maxNum = e.target.getAttribute('maxlength');` that way I can use any max length number in my code and this should work. – lharby Jul 12 '21 at 08:48
4

In my experience most issues where people are asking why maxlength is ignored is because the user is allowed to input more than the "allowed" number of characters.

As other comments have stated, type="number" inputs do not have a maxlength attribute and, instead, have a min and max attribute.

To have the field limit the number of characters that can be inserted while allowing the user to be aware of this before the form is submitted (browser should identify value > max otherwise), you will have to (for now, at least) add a listener to the field.

Here is a solution I've used in the past: http://codepen.io/wuori/pen/LNyYBM

M Wuori
  • 91
  • 2
  • min and max are as good as useless here, they do not prevent the user from typing an inifinite amount of numbers in the input field. – andreszs Feb 21 '18 at 14:41
  • True. The only time you see them in action is when you're using the arrow keys or the up/down controllers (in Chrome, etc.). You can still use these attributes to tie into your subsequent validation, which has worked for me. This allows you to control limits via markup (i18n, etc.) vs. JS only. – M Wuori Sep 18 '18 at 05:55
4

maxlength ignored for input type="number"

That's correct, see documentation here

Instead you can use type="text" and use javascript function to allow number only.

Try this:

function onlyNumber(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
            return false;
        }
    return true;
}
<input type="text" maxlength="4" onkeypress="return onlyNumber(event)">
frianH
  • 7,295
  • 6
  • 20
  • 45
3

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
3

The absolute solution that I've recently just tried is:

<input class="class-name" placeholder="1234567" name="elementname"  type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />
Mr. Benedict
  • 809
  • 2
  • 10
  • 15
  • Because this is generic JS, it'll work everywhere. I'm working on a project using Angular 5 and it works like a charm. You can probably spend 10 minutes creating a service in your angular code so you can reuse it throughout your project. – Mr. Benedict Oct 16 '18 at 12:21
3

Done! Numbers only and maxlength work perfect.

<input  maxlength="5" data-rule-maxlength="5" style="height:30px;width: 786px;" type="number"  oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
Pit
  • 395
  • 2
  • 11
3

This code worked quite nicely for me.

In the input with type="number", you can add the following attribute:

oninput="constrainUserInput(this.id)"

The full input will look like this:

<input type="number" class="test_css" maxlength="4" oninput="constrainUserInput(this.id)" id="flight_number" name="number"/>

Note: You must assign your input and ID for this method to work

Then you can add the following JavaScript to your HTML, which basically replaces any characters that exceed your maxlength attribute with an empty quote (essentially removing them):

function constrainUserInput(id) {
  let input = document.getElementById(id);
  let value = input.value;
  if (value.length > input.maxLength) {
    input.value = value.substring(0, input.maxLength);
  }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
3

<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>

Use type number with min and handle max with onKeyPress

<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>
M Komaei
  • 7,006
  • 2
  • 28
  • 34
2

As per the Neha Jain's answer above ,I just added below code to common area

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

});

then you can use maxlength="4" like text type fields.

Roshan Perera
  • 780
  • 7
  • 12
1

<input type="number"> is just that... a number input (albeit, unconverted from a string to float via Javascript).

My guess, it doesn't restrict characters on key input by maxLength or else your user could be stuck in a "key trap" if they forgot a decimal at the beginning (Try putting a . at index 1 when an <input type"text"> "maxLength" attr has already been reached). It will however validate on form submit if you set a max attribute.

If you're trying to restrict/validate a phone number, use the type="tel" attr/value. It obeys the maxLength attr and brings up the mobile number keyboard only (in modern browsers) and you can restrict input to a pattern (i.e. pattern="[0-9]{10}").

daleyjem
  • 2,335
  • 1
  • 23
  • 34
0

I was able archive it using this.

<input type="text" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" maxlength="4">
Thilina Koggalage
  • 1,044
  • 8
  • 16
0

I had problem with this on django forms.Form this is the code of how I solved it.

HTML

<input type="tel" maxlength="6" oninput="this.value=this.value.replace(/[-]/g,'');"></input> <!-- I needed to remove the "-" sinc tell field accepts it. -->

Django form

class TokenForm(forms.Form):
code = forms.CharField(
    required=True,
    label="Enter 6 digit confirmation code",
    widget=forms.TextInput(
        attrs={
            "class": "form-control",
            "placeholder": "Enter 6 digit code",
            "type": "tel",
            "maxlength":"6", 
            "oninput":"this.value=this.value.replace(/[-]/g,'');"
        }
    ),
)
0

Try it out on React.

<input 
   onInput={(e) => {
   if (e.target.value.length > e.target.maxLength)
   e.target.value = e.target.value.slice(0,e.target.maxLength);
}}
    type = "number"
    maxlength = {6}
 />
Sherothkar
  • 109
  • 8
-1

I will make this quick and easy to understand!

Instead of maxlength for type='number' (maxlength is meant to define the maximum amount of letters for a string in a text type), use min='' and max='' .

Cheers

Dat Boi
  • 595
  • 3
  • 12
-2

maxlenght - input type text

<input type="email" name="email" maxlength="50">

using jQuery:

$("input").attr("maxlength", 50)

maxlenght - input type number

JS

function limit(element, max) {    
    var max_chars = max;
    if(element.value.length > max_chars) {
        element.value = element.value.substr(0, max_chars);
    } 
}

HTML

<input type="number" name="telefono" onkeydown="limit(this, 20);" onkeyup="limit(this, 20);">
Hernaldo Gonzalez
  • 1,977
  • 1
  • 21
  • 32