15

I was trying to set an input number (html) to only positive numbers and I found this fine solution:

    <input type="number" name="test_name" min="0" oninput="validity.valid|| 
    (value='');">

Can anyone tell me how does oninput="validity.valid||(value=''); works? How does it restrict the input to only positive numbers.

Thank you!

Juan Pablo
  • 177
  • 1
  • 1
  • 10
  • 1
    Full guide here: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation – Blue Dec 09 '18 at 23:49

2 Answers2

9

min="0" only accept numbers greater than zero. So when the user enters a value (oninput), either it is valid (validity.valid) or (||) the value is replaced by an empty string (value='').


Edit:

validity.valid is falsy because of min="0" as we can see in the doc under the rangeUnderflow property:

"if the value is less than the minimum specified by the min attribute".

Maarti
  • 3,600
  • 4
  • 17
  • 34
  • 2
    So, the `validity.valid` is related somehow to the constraint `min=0`? – Juan Pablo Dec 10 '18 at 00:22
  • 1
    Yes, as we can see [here](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) in **rangeUnderflow**, the ValidityState is falsy "if the value is less than the minimum specified by the min attribute". – Maarti Dec 10 '18 at 00:25
  • 1
    Oh, I see now. Thank you very much, brother, you helped me a lot there. – Juan Pablo Dec 10 '18 at 00:30
2

This event is sent when a user enters text in a input.

This event is onlycalled when the text displayed would change, thus it is not called when the user presses non-displayable keys.

So what is does is to check the validity.valid property to make the validation.

Yoarthur
  • 909
  • 9
  • 20
  • can i ask you?. Where do you see such thing? @JuanPablo – Yoarthur Dec 10 '18 at 00:30
  • I saw it in this post [link](https://stackoverflow.com/questions/19233415/how-to-make-type-number-to-positive-numbers-only/46334535#46334535?newreg=70f526a3d5e449f1ab3401824e32906f) – Juan Pablo Dec 10 '18 at 00:44