For element,
maxlength
is not working. How can I restrict the maxlength
for that number element?
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
More relevant attributes to use would be min
and max
.
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);
}
}
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.
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);"
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);
}
})
});