Every submittable control that isn't barred (disabled, readonly, hidden inputs, non-submit buttons) is a candidate for constraint validation; willValidate tells you which. Its attributes define constraints, and element.validity, a ValidityState, reports each failure as a flag:
valueMissing(required),typeMismatch(email,url),patternMismatch(pattern)tooLong,tooShort(maxlength,minlength),rangeUnderflow,rangeOverflow,stepMismatch(min,max,step)badInput(text the browser can't convert, such as letters in a number field)customError, set bysetCustomValidity(message)valid: true when none of the above is
checkValidity() returns the result and fires a cancelable, non-bubbling invalid event at each failing control. reportValidity() does the same, then shows the browser's message for a control whose event wasn't cancelled; both browsers focused the first such control. Submitting a form runs the interactive version: if anything is invalid, no submit event fires and nothing is sent. novalidate on the form, or formnovalidate on the button, skips that step.
To customise:
- Your own rules:
setCustomValidity("That name is taken")makes the control invalid with that message. It stays set until you callsetCustomValidity(""), so update it on everyinput. - Your own error UI: listen for
invalidin the capture phase, callpreventDefault()to suppress the browser's bubble, and rendervalidationMessageyourself. - Styling:
:invalidmatches from page load, so empty required fields look wrong before anyone touches them.:user-invalidmatches only after the user has changed and left the field, or tried to submit.
Native validation is a usability layer only; the server must still validate.