Rivi
Rivi

Reputation: 791

Difference between checkValidity & validity

I've noticed there are 2 ways for an input element validation:

  1. element.checkValidity().
  2. 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

Answers (1)

str
str

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.

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().

Upvotes: 10

Related Questions