Use required, pattern and other attributes for built-in checks, setCustomValidity() for your own wording, and the :user-invalid selector to show errors only after someone has interacted.
The short answer
#Let HTML attributes such as required, pattern and type="email" do the checking. To change the wording of the error, call setCustomValidity() with your message when the field is invalid, and with an empty string when it is valid. Style errors with :user-invalid so fields do not look broken before anyone has typed.
_10<label for="postcode">Postcode</label>_10<input id="postcode" name="postcode" required_10 pattern="[A-Za-z]{1,2}[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}"_10 autocomplete="postal-code">
_13const postcode = document.querySelector("#postcode");_13_13function checkPostcode() {_13 postcode.setCustomValidity("");_13 if (postcode.validity.valueMissing) {_13 postcode.setCustomValidity("Enter your postcode.");_13 } else if (postcode.validity.patternMismatch) {_13 postcode.setCustomValidity("Enter a UK postcode, like SW1A 1AA.");_13 }_13}_13_13postcode.addEventListener("input", checkPostcode);_13checkPostcode();
Why it happens
#Browsers run constraint validation on every form control. Each control has a validity object with flags such as valueMissing, typeMismatch, patternMismatch and tooShort. When the form is submitted and any flag is true, the browser blocks the submit, focuses the first invalid field and shows its own message bubble.
Those default messages are generic and depend on the browser and language. setCustomValidity() replaces the message, but it also does something people miss: any non-empty string marks the field as invalid, whatever its value. That is why you must reset it to an empty string before checking again, or the field can never become valid.
How to fix it
#Use the built-in attributes first
Many rules need no JavaScript at all.
_10<input type="email" name="email" required>_10<input type="text" name="username" required minlength="3" maxlength="20">_10<input type="number" name="guests" min="1" max="10">
The pattern attribute must match the whole value; you do not need to add start and end anchors. Modern browsers compile it with the regular expression v flag, so some characters inside a character class, such as a literal hyphen, need escaping: write [\w\-] rather than [\w-].
Set your own message with setCustomValidity
Check the specific validity flags and set a message that tells people how to fix the problem, as in the short answer. Run the check once on load, so an empty required field already has your message on the first submit, and again on every input event.
You can also use it for rules HTML cannot express, such as two password fields matching:
_11const password = document.querySelector("#password");_11const confirm = document.querySelector("#confirm");_11_11function checkMatch() {_11 confirm.setCustomValidity(_11 confirm.value === password.value ? "" : "Passwords do not match."_11 );_11}_11_11password.addEventListener("input", checkMatch);_11confirm.addEventListener("input", checkMatch);
Style errors with :user-invalid
The :invalid selector matches as soon as the page loads, so every empty required field looks wrong before anyone touches it. :user-invalid only matches after the user has interacted with the field or tried to submit. It has been Baseline since late 2023 and works in all current major browsers.
_10input:user-invalid {_10 border-color: #c0392b;_10 outline-color: #c0392b;_10}_10_10input:user-valid {_10 border-color: #2e7d32;_10}
Show messages inline instead of in a bubble
If you want messages next to each field, add novalidate to the form. This turns off the browser bubbles but keeps the validation API, so you can read validationMessage yourself.
_10<form id="signup" novalidate>_10 <label for="email">Email</label>_10 <input id="email" type="email" required aria-describedby="email-error">_10 <p id="email-error" class="error" aria-live="polite"></p>_10 <button>Sign up</button>_10</form>
_12const form = document.querySelector("#signup");_12_12form.addEventListener("submit", (event) => {_12 for (const field of form.elements) {_12 const error = document.getElementById(`${field.id}-error`);_12 if (error) error.textContent = field.validationMessage;_12 }_12 if (!form.checkValidity()) {_12 event.preventDefault();_12 form.querySelector(":invalid")?.focus();_12 }_12});
Common pitfalls
#- Calling
setCustomValidity("Some message")and never clearing it. The field stays invalid forever. - Styling
:invalid, which shows errors on page load. Use:user-invalidinstead. - Treating browser validation as security. Anyone can bypass it, so validate again on the server.
- Expecting
type="email"to check that an address exists. It only checks the rough shape. - Forgetting the
vflag rules inpattern, which can make the pattern silently stop working. - Messages that only say "Invalid". Tell people what to type instead.
Related reading
#Was this resource helpful?