ab11
ab11

Reputation: 20100

HTML5 number min attribute doesn't prevent user entry below minimum?

I realize there are other solutions to this, but I am trying to use the HTML5 min attribute to prevent users from entering 0 in a text field. The below markup gives a text field with nifty up/down arrows for number selection; if I press the down arrow the value will not go below 1. But I can still manually enter 0 into the field. Is this expected behavior? Is there an HTML5 technique to prevent entering numbers less than a certain minimum?

<input type="number"  min="1" />

Upvotes: 4

Views: 3908

Answers (2)

Abbas Amiri
Abbas Amiri

Reputation: 3204

In HTML5, you can have a number input field as a spinner which you have up and down arrow at the right of the textbox to increase or decrease the number value, but it doesn't prevent you to enter a wrong value. In fact, it validates the value based upon the min and max attributes.

The accepted answer at Maximum and minimum values in a textbox offers a way to prevent user to enter a wrong value.

Upvotes: 0

BlackHawkRider
BlackHawkRider

Reputation: 61

When you use the min attribute on input type number, you can limit user from going below the min or above the max through the arrows. However, users can try to input it an invalid value directly but it will not pass. You can see the what happens when you put in an invalid value through this:

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_max_min

If you don't like this, you can always go for the javascript method like this:

<script>
  function validateNum(input) {
    if (input.value < 1) input.value = 1;
  }
</script>

<input type="number" onchange="validateNum(this);" />

Not sure if the above code works because I just simply typed up one without actually testing it, but you should be able to understand where I am going at with this.

Upvotes: 4

Related Questions