Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 785
Rivi Avatar asked Mar 08 '23 01:03

Rivi


1 Answers

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

like image 75
str Avatar answered Mar 16 '23 15:03

str