Forms & Validation
novalidate and the form Attribute
novalidateon<form>disables built-in browser validation (useful for custom validation logic).- The
formattribute on inputs (e.g.,<input form="myform">) allows inputs outside the<form>element to be associated with it.
required vs pattern
required: Ensures the field is not empty.pattern: Validates input against a regular expression (e.g.,pattern="[0-9]{5}"for ZIP code).
Both trigger native validation messages; pattern is more flexible for format checks.
Autocomplete, Autofocus, Placeholder
autocomplete: Hints to browser (e.g.,autocomplete="email"improves UX on login forms).autofocus: Automatically focuses an input when page loads (use sparingly, only one per page).placeholder: Shows hint text that disappears on focus — not a substitute for<label>.
Constraint Validation API
JavaScript interface for custom validation logic:
const input = document.querySelector('#email');
input.addEventListener('input', () => {
if (input.validity.typeMismatch) {
input.setCustomValidity('Please enter a valid email address');
} else {
input.setCustomValidity('');
}
});
Key properties on input.validity: valueMissing, typeMismatch, patternMismatch, tooLong, tooShort, rangeOverflow, rangeUnderflow, stepMismatch, customError, valid.