It depends on whether you want an int or float field. Here's what the two would look like:
<input type="number" name="int-field" id="int-field" placeholder="positive int" min="1" step="1">
<input type="number" name="float-field" id="float-field" placeholder="positive float" min="0">
The int field has the correct validation attached to it, since its min is 1. The float field accepts 0, however; to deal with this, you can add one more constraint validator:
function checkIsPositive(e) {
const value = parseFloat(e.target.value);
if (e.target.value === "" || value > 0) {
e.target.setCustomValidity("");
} else {
e.target.setCustomValidity("Please select a value that is greater than 0.");
}
}
document.getElementById("float-field").addEventListener("input", checkIsPositive, false);
JSFiddle here.
Note that none of these solutions completely prevent the user from trying to type in invalid input, but you can call checkValidity
or reportValidity
to figure out whether the user has typed in valid input.
Of course, you should still have server-side validation because the user can always ignore client-side validation.