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
Advertisement
Answer
I don’t think there is a solution directly with HTML; the max
and min
attributes only work when clicking the up arrow and down arrow keys. Check out the post in the references section for more information. The image below shows that the input does not change when the up arrow button is clicked, since the max
attribute is 100:
In the solution below, when the input
event of the <input>
element is triggered, the data input is checked by checking the max
attribute with the isValid()
method. You can change the disabled
property of the submit button according to the result returned by the isValid()
method.
const inputElement = document.querySelector('input'); function isValid(value){ if(parseInt(value) <= inputElement.getAttribute('max')) return true; return false; } inputElement.addEventListener('input', function () { if(isValid(this.value)) console.log("true"); else console.log("false"); });
<input type="number" max="100">