'input type number - max value
I have an input
<input type="number" max="100">
However, if the user write manually for example 200, the input accept it. Is it something normal ?
I can validate the entry with javascript but if there is a build in in the html input it would be great :)
Thanks
Solution 1:[1]
There is actually no "native" HTML way outside a form post to avoid the faulty manual entry. You could do something like this (here jquery code):
$('input[type="number"]').on('change input keyup paste', function () {
if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
});
This code applies to all inputs of type number in case of keyboard input, pasting, changing a validation method that checks, whether a max value exists and if so Math.min() returns the lowest-valued number passed into it. If the value is not a number 0 is returned.
See a demo at JSFiddle
In Vanilla JavaScript the handler would look like this:
var numElement = document.querySelector('input[type="number"]')
numElement.addEventListener('change', validateMax);
numElement.addEventListener('input', validateMax);
numElement.addEventListener('keyup', validateMax);
numElement.addEventListener('paste', validateMax);
function validateMax() {
if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
}
See a demo of the vanilla version at JSFiddle
This handler should do the trick.
Solution 2:[2]
If you are using form, you can just mark it as required and the form does the validation for you.
document.getElementById("myForm").addEventListener("submit", function (event) {
event.preventDefault();
console.log(document.getElementById("myNumber").value);
});
<form id="myForm">
<input id="myNumber" name="myNumber" type="number" max="100" required >
<button>Send It</button>
</form>
Now if you want to know if it is valid in JavaScript directly there is built in methods for that
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
console.log(document.getElementById("myNumber").value);
});
document.getElementById("check").addEventListener("click", function(event) {
console.log("form: ", document.getElementById("myForm").checkValidity());
console.log("input: ", document.getElementById("myNumber").validity.valid);
});
<form id="myForm">
<input id="myNumber" name="myNumber" type="number" max="100" required>
<button>Send It</button>
</form>
<button type="button" id="check">Check It</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sercan |
| Solution 2 | epascarello |
