Sub topic 8
Custom messages and rules with setCustomValidity
This chapter assumes you know the built-in constraint attributes (required, pattern, min, max) and how to read field.validity and field.validationMessage. Here you will replace the browser's default messages and add rules that HTML attributes cannot express.
What setCustomValidity does
setCustomValidity(message) is a method on form controls. It changes the control's state in two ways:
- A non-empty string marks the control invalid.
validity.customErrorbecomestrue, andvalidationMessagereturns your text. - An empty string removes the custom error. The control is then judged only by the built-in constraints.
The browser does not clear a custom error for you. Once you set one, it stays until you set an empty string. Because of this, the usual pattern is to re-run your rule on every change and set either a message or ''.
Replacing a default message
The default text for a pattern mismatch is generic. You can supply a clearer one by checking validity.patternMismatch and writing your own message.
<form id="signup" action="/signup" method="post">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+">
<label for="password">Password</label>
<input id="password" name="password" type="password" required minlength="8">
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password" required>
<button type="submit">Sign up</button>
</form>
<script>
const username = document.getElementById('username');
username.addEventListener('input', () => {
// Clear first. Otherwise a stale custom error would make
// validity.patternMismatch report the wrong state.
username.setCustomValidity('');
if (username.validity.patternMismatch) {
username.setCustomValidity('Use lowercase letters, digits, and underscores only.');
} else if (username.validity.tooShort) {
username.setCustomValidity('Usernames need at least 3 characters.');
}
});
</script>The call to setCustomValidity('') comes first for a reason. The built-in flags such as patternMismatch are computed independently of the custom error, so they stay accurate. But field.validity.valid and checkValidity() will report false as long as your old message remains. Clearing first keeps the logic simple.
Adding a rule HTML cannot express
Matching two fields is the classic case. No attribute can say "this value must equal that one," so you write the check yourself.
const password = document.getElementById('password');
const confirm = document.getElementById('confirm');
function checkMatch() {
confirm.setCustomValidity(
confirm.value === password.value ? '' : 'Passwords do not match.'
);
}
password.addEventListener('input', checkMatch);
confirm.addEventListener('input', checkMatch);Both fields need listeners. If the user fixes the first password after typing the confirmation, only the password listener can clear the stale error on confirm. The next chapters on cross-field rules build on this pattern.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Never passing `''` | Field stays invalid after the user corrects it, and the form will not submit | Clear the error on every `input` event |
| Setting the message only on `submit` | Message appears late, and `:user-invalid` styling does not match | Validate on `input`, and also on `submit` if needed |
| Listening on only one of two related fields | Stale error after editing the other field | Attach the same handler to both |
| Using a custom message for server-only facts | The error disappears or never appears on the next load | Return server errors in the response (see the server validation chapter) |
Showing the message
Setting a custom error does not display anything by itself. The browser shows it when the user tries to submit, or when your code calls reportValidity(). You can also read validationMessage and write it into your own error element, as in the submit handler from the previous chapter. In both cases the text you set is what the user sees.
Exercise
A user types "abc" in a confirm-password field, and your handler calls confirm.setCustomValidity('Passwords do not match.'). They then fix the password field above it so both values match, but the form still will not submit. What is the likely cause, and how do you fix it?
Show answer
The confirm field still holds its old custom error, because only the confirm field's listener clears it. Fix this by also running the check (which passes an empty string when the values match) from an input listener on the password field.