maxlength ignored for input type="number" in Chrome

HtmlGoogle Chrome

Html Problem Overview


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"/>

Html Solutions


Solution 1 - Html

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">

Solution 2 - Html

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"
 />

Solution 3 - Html

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;" />

Solution 4 - Html

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;" />

Solution 5 - Html

You can use the min and max attributes.

The following code do the same:

<input type="number" min="-999" max="9999"/>

Solution 6 - Html

> 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

Solution 7 - Html

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)}/>

Solution 8 - Html

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"
 />

Solution 9 - Html

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 :)

Solution 10 - Html

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

<input type="tel" maxlength="4" />

Solution 11 - Html

try use tel :

 maxlength="5" type="tel"

Solution 12 - Html

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.

Solution 13 - Html

<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

Solution 14 - Html

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}
/>

Solution 15 - Html

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"/>

Solution 16 - Html

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

Solution 17 - Html

>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)">

Solution 18 - Html

Try this,

<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />

Solution 19 - Html

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);
    }
  };

Solution 20 - Html

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='');"> 

Solution 21 - Html

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();

Solution 22 - Html

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.

Solution 23 - Html

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');" />

Solution 24 - Html

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>

Solution 25 - Html

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" />

Solution 26 - Html

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.

Solution 27 - Html

<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}").

Solution 28 - Html

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);
  }
}

Solution 29 - Html

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,'');"
        }
    ),
)

Solution 30 - Html

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

Solution 31 - Html

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">

Solution 32 - Html

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);">

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrajila V PView Question on Stackoverflow
Solution 1 - HtmlAndré DionView Answer on Stackoverflow
Solution 2 - HtmlNeha JainView Answer on Stackoverflow
Solution 3 - HtmlVikasdeep SinghView Answer on Stackoverflow
Solution 4 - HtmlMaycow MouraView Answer on Stackoverflow
Solution 5 - HtmlinonView Answer on Stackoverflow
Solution 6 - HtmlMasoodView Answer on Stackoverflow
Solution 7 - HtmlmcnkView Answer on Stackoverflow
Solution 8 - HtmlPeterView Answer on Stackoverflow
Solution 9 - HtmlMohammad MahrozView Answer on Stackoverflow
Solution 10 - HtmlshinobiView Answer on Stackoverflow
Solution 11 - HtmlarisView Answer on Stackoverflow
Solution 12 - Htmlharley81View Answer on Stackoverflow
Solution 13 - HtmlSurya R PraveenView Answer on Stackoverflow
Solution 14 - HtmlofarukcakiView Answer on Stackoverflow
Solution 15 - HtmlJonathan Akwetey OkineView Answer on Stackoverflow
Solution 16 - HtmlM WuoriView Answer on Stackoverflow
Solution 17 - HtmlfrianHView Answer on Stackoverflow
Solution 18 - HtmlCodemakerView Answer on Stackoverflow
Solution 19 - HtmlDremiqView Answer on Stackoverflow
Solution 20 - HtmlJ_KView Answer on Stackoverflow
Solution 21 - HtmlPhilll_tView Answer on Stackoverflow
Solution 22 - HtmlpwnallView Answer on Stackoverflow
Solution 23 - HtmlPitView Answer on Stackoverflow
Solution 24 - HtmlAkbaraliView Answer on Stackoverflow
Solution 25 - HtmlMr. BenedictView Answer on Stackoverflow
Solution 26 - HtmlRoshan PereraView Answer on Stackoverflow
Solution 27 - HtmldaleyjemView Answer on Stackoverflow
Solution 28 - HtmlGraham BillingtonView Answer on Stackoverflow
Solution 29 - HtmlCynthia OnyilimbaView Answer on Stackoverflow
Solution 30 - HtmlDat BoiView Answer on Stackoverflow
Solution 31 - HtmlKogaView Answer on Stackoverflow
Solution 32 - HtmlHernaldo GonzalezView Answer on Stackoverflow