What's the purpose of setCustomValidity() and reportValidity()?
input.addEventListener('input', e => {
if (e.target.value.length > 0) {
e.target.setCustomValidity('');
} else {
e.target.setCustomValidity('This field is required');
}
e.target.reportValidity();
});
setCustomValidity() and reportValidity() are part of the Constraint Validation API: 1) setCustomValidity() sets a custom validation message - empty string means valid, any string means invalid, 2) reportValidity() displays the validation message to the user and returns boolean validity status, 3) This provides native validation UI consistent with browser standards, 4) Supports accessibility as screen readers can access these messages, 5) Integrates with form validation and :invalid CSS pseudo-class.