How can I set max-length in an HTML5 "input type=number" element?
Solution 1
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:
Solution 2
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.
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);
}
}
Solution 3
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.
Solution 4
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.
Solution 5
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
Prasad
Updated on July 16, 2022Comments
-
Prasad almost 2 years
For
<input type="number">
element,maxlength
is not working. How can I restrict themaxlength
for that number element? -
Prasad over 12 yearsKrister, this worked. Also as @Andy said i have used the oninput to slice the additional numbers. Reference mathiasbynens.be/notes/oninput
-
DA. over 12 yearsThis 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.
-
deniz almost 11 yearsOne 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".
-
hawkharris almost 10 yearsI'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.
-
Duane almost 10 years@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.
-
Quentin S. almost 10 yearsDA : sure, but you could use
min="-999" max="999"
to fakemaxlength="3"
. -
0112 over 9 yearsIf 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.
-
Andrew over 9 yearsThis is a good solution, but I find that object.value.length returns 0 if there are any non-numeric values entered.
-
David Refoua over 9 years@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.
-
Pacerier over 9 years@Andy, Obviously the question is looking for a non-JS way to do
maxlength
............. -
Andy E over 9 years@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.
-
Codemonkey almost 9 yearsI 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.
-
Cyclonecode almost 9 years@Codemonkey - Even if a user is able to manually enter a value that is greater than
max
or lower thanmin
the form will not be submitted. Instead you will get a popup that tells you to enter a value inside the specified range. -
Codemonkey almost 9 yearsHardly a good user experience compared to a JS maxlength simulator though
-
Qwertiy almost 9 yearsNope. Try to paste a value.
-
Don Cheadle over 8 years@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 sayPlease enter a valid value. Closest numbers are 3 and 4
. So.. please delete your comment so as not to confuse others -
diazdeteran over 8 yearsThe pattern attribute is not supported in IE9 and earlier versions, and it has partial support in Safari: caniuse.com/#feat=input-pattern
-
Chris Panayotoff over 8 yearsYes, thanks for pointing, but we dropped IE9 support ( cutting the mustard from it ), and I prefer it over JS methods. Depends on the project.
-
Christophe Debove over 8 yearsWith your solution you can't use backspace once you reach 2 characters. but I miss few thing for a functional solution
-
Jessica over 8 yearsYou can easily paste characters in.
-
PieBie over 8 yearsThis 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.
-
David Refoua over 8 years@PieBie Dude, this code is for 3+ years ago. Use jQuery instead.
-
PieBie over 8 yearsyeah, I know that, but beginners might still just copy-paste it.
-
Pradeep Kumar over 8 yearsslice will delete characters without end user knowledge when inserted in-between. whereas max-length will block.
-
thdoan over 8 years@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. -
Pradeep Kumar over 8 yearsyes maxlength is not supported for number inputs.. this code is gud but this code doesn't match the maxlength's property exactly..
-
Rupesh Arora about 8 yearsInstead of onKeyDownyou should use onKeyPress.
-
Arijoon about 8 yearswon't work if you highlight the text and press a character (i.e. to replace the content of the input)
-
Akshay almost 8 yearsvalidate this if this is not from following keys stackoverflow.com/a/2353562/1534925
-
nnnnnn almost 8 years"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 asmax
andmin
, but it just doesn't... -
Cyclonecode almost 8 years@nnnnnn - Well the question in not tagged with either ajax or js?
-
xoxel over 7 years... Great, but you don't need min and max anymore dude. (just saying)
-
Robert McKee over 7 years@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.
-
thdoan over 7 years@TobiasGaertner
type="number"
takes care of that :). -
Tobias Gaertner over 7 years@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.
-
markus s over 7 years@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?
-
Philll_t over 7 yearsWhat do you mean "delivers 2"?
-
markus s over 7 yearsPhill_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 over 7 yearsAs 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: stackoverflow.com/a/41871960/1312012
-
saiyancoder over 7 yearsThis solutions was exactly what I needed. If someone is using Ionic 2, the directive should be keydown. Like this:
<ion-input type="number" (keydown)="elem.value.length !== 4" [(ngModel)]="elem.value" [ngModelOptions]="{ standalone: true }"></ion-input>
-
Edub about 7 yearsThe 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
-
Prasad Shinde about 7 yearsI tried with simple version javascript. If you want you can see using Run code snippet. As such I didnt find any limitation.
-
DNKROZ almost 7 years@xoxel you do if you want the warning message to still display
-
Claudio almost 7 yearsDidn't find any limitations either. It stops at 7 digits. I'm using this solution for my code.
-
Stavm over 6 yearsproblem with
keydown
is that you can't use backspace at max characters. problem withkeypress
is that you can copy+paste beyond max characters. -
apereira almost 6 yearsif used with pattern="[0-9]*" the extra symbols will be disabled
-
brt over 5 yearsA user isn't prevented from entering non-numeric characters with this. They can enter 2 of any char. The
pattern
only causes validation highlighting. -
TrOnNe over 5 yearsit doesn't correctly answer the question, but voted up as it has solved my problem :)
-
Capsule over 5 yearsBut 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...
-
Aakash Thakur about 5 yearsdoesn't work on android chrome. onkeypress has some issues with this.
-
spjpgrd about 5 yearsThis is one of the best summaries of user-friendly numeric input modes: 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:
<input type="number" inputMode="numeric" pattern="[0-9]*" min="1" max="2112">
Then you can enhance this with some JavaScript if you need 🙃 -
Insomnia88 over 4 yearsThere 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.
-
Prasad Shinde over 4 years@Insomnia88 ,@edub what if we write function and check necessary conditions...
-
oriadam over 4 yearsfor the sake of generalization i'd do
onKeyUp="if(this.value>this.max)this.value=this.max;if(this.value<this.min)this.value=this.min;"
-
oriadam over 4 yearstested on Android 9 (Nokia 8) but i get the regular keyboard :( any ideas?
-
Omiod over 3 yearsThis is the best reply, but I suggest to use onChange instead of keyUp as it is too much aggressive while typing.
-
user1438038 over 2 years@spjpgrd: Good find, but
type
should betext
and notnumber
, as per article that you linked to:<input type="text" inputmode="numeric" pattern="[0-9]*" min="1" max="999" />
-
Bogdan Onyshenko over 2 yearsOn 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.