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.
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.
ValidityState.valid
:
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With