Reputation: 791
I've noticed there are 2 ways for an input element validation:
element.checkValidity()
.element.validity.valid
. I understand that validity
is an object while checkValidity
is a function but I don't understand when should I use either one of them and what is the key difference between them.
Upvotes: 4
Views: 5154
Reputation: 44989
HTMLSelectElement.checkValidity()
:
The
HTMLSelectElement.checkValidity()
method checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
Is a Boolean indicating the element meets all constraint validations, and is therefore considered to be valid.
So the main difference is that checkValidity()
will also fire an "invalid" event. If you just want to know whether the value is valid, use ValidityState.valid
. But if you want to change the form state to invalid, use checkValidity()
.
Upvotes: 10