Prevent negative inputs in form input type="number"?

Issue

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 negative number.

Is there any other way to solve this without writing a validation function?

Solution

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>

Answered By – Mikel Rychliski

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.