1

I was trying to restrict input type="number"(html) to only integers numbers, and I found this solution:

<input id="test" type="number" min="1" step="1" oninput="validity.valid|| 
    (value='');">

Can anyone tell me how can i do this in js code oninput="validity.valid||(value='')

Olatunji
  • 35
  • 9
  • You can read more about validity state on [mdn](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) – evolutionxbox Jun 04 '21 at 09:37
  • @evolutionxbox i already did, but i got confused when i wanted to do it in javascript, kinda don\t understand how can i do this. – Olatunji Jun 04 '21 at 09:38
  • Does this answer your question? [How does validity.valid works?](https://stackoverflow.com/questions/53697812/how-does-validity-valid-works) – Sudhir Ojha Jun 04 '21 at 09:39
  • @SudhirOjha well i read it, and i kinda understand how it works, but i don't understand how to do this same in js code – Olatunji Jun 04 '21 at 09:40

1 Answers1

0

This is using the Constraint Validation API: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#the_constraint_validation_api

validity is a property on your input element that returns the state: https://developer.mozilla.org/en-US/docs/Web/API/ValidityState#properties

validity.valid essentially means "this is correct"

validity.valid||(value='')

is standard "or" syntax. Either take the valid result, or set the input value to an empty string

divillysausages
  • 7,883
  • 3
  • 25
  • 39
  • So my js code should look kinda like this, jQuery('#testTest').on('input', '#test', function () { validity.valid || (value=' ') } – Olatunji Jun 04 '21 at 09:44
  • https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#implementing_a_customized_error_message has a good example of what you're looking for. Basicially `validity` is a property on your `input` - so it'll be something like `if(myInput.validity.valid) console.log('ok')` – divillysausages Jun 04 '21 at 09:48
  • if you could made example how do this this with js, i kinda still don't get it – Olatunji Jun 04 '21 at 10:52