I want to restrict user input to positive numbers in an html form.
I know you can set min=\"0\", however it is possible to bypass this by manually entering a negati
This uses Javascript, but you don't have to write your own validation routine. Instead just check the validity.valid property. This will be true if and only if the input falls within the range.
<html>
<body>
<form action="#">
<input type="number" name="test" min=0 oninput="validity.valid||(value='');"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The following script will only allow numbers or a backspace to be entered into the input.
var number = document.getElementById('number');
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<input type="number" id="number" min="0">