More HTML answers

by Danny
Published 2 min read

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">


_13
const postcode = document.querySelector("#postcode");
_13
_13
function 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
_13
postcode.addEventListener("input", checkPostcode);
_13
checkPostcode();

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:


_11
const password = document.querySelector("#password");
_11
const confirm = document.querySelector("#confirm");
_11
_11
function checkMatch() {
_11
confirm.setCustomValidity(
_11
confirm.value === password.value ? "" : "Passwords do not match."
_11
);
_11
}
_11
_11
password.addEventListener("input", checkMatch);
_11
confirm.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.


_10
input:user-invalid {
_10
border-color: #c0392b;
_10
outline-color: #c0392b;
_10
}
_10
_10
input: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>


_12
const form = document.querySelector("#signup");
_12
_12
form.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-invalid instead.
  • 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 v flag rules in pattern, which can make the pattern silently stop working.
  • Messages that only say "Invalid". Tell people what to type instead.
#

Was this resource helpful?