Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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" />
like image 952
ab11 Avatar asked Oct 28 '25 18:10

ab11


1 Answers

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.

like image 181
BlackHawkRider Avatar answered Oct 31 '25 10:10

BlackHawkRider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!