Sub topic 8
Custom messages and rules with setCustomValidity
This chapter assumes you know the built-in constraint attributes (required, minlength, pattern and so on). It also assumes you have used validity, checkValidity() and reportValidity() from the previous chapter, and that you can attach event listeners in JavaScript. Here you will replace the browser's default messages and add rules the attributes cannot express.
What setCustomValidity does
setCustomValidity(message) is a method on form controls such as input, select, textarea and button. It takes a string and has two effects.
- A non-empty string puts the control into a custom error state.
validity.customErrorbecomestrue,validity.validbecomesfalse, andvalidationMessagereturns your text. - An empty string clears the custom error. The control is then judged only by its built-in constraints.
The method does not display anything by itself. It only changes the control's state. The message appears when something asks the browser to report validity: a submit attempt, a call to reportValidity(), or a call to checkValidity() that fires an invalid event you handle yourself.
The error is sticky
A custom error stays until you clear it. The browser never clears it for you, not even when the user edits the field. If you set a message once and never reset it, the form cannot be submitted, and the user cannot tell why.
For that reason, every rule you write with setCustomValidity follows one pattern. On each relevant event, compute the answer and call the method with either a message or an empty string. Never call it only on the failure path.
function check(field) {
const problem = findProblem(field.value); // returns a string, or '' when fine
field.setCustomValidity(problem);
}A complete working example
This page adds a rule that the attributes cannot express: a password must contain a digit, and the confirmation field must match it. Save it as an HTML file and open it in a browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom validity demo</title>
</head>
<body>
<form id="signup" action="/signup" method="post">
<label for="password">Password</label>
<input id="password" name="password" type="password" required
minlength="8" autocomplete="new-password">
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password" required
autocomplete="new-password">
<button type="submit">Create account</button>
</form>
<script>
const password = document.getElementById('password');
const confirm = document.getElementById('confirm');
function checkPassword() {
password.setCustomValidity(
/\d/.test(password.value) ? '' : 'Include at least one digit.'
);
}
function checkMatch() {
confirm.setCustomValidity(
confirm.value === password.value ? '' : 'Passwords do not match.'
);
}
password.addEventListener('input', () => {
checkPassword();
checkMatch(); // the confirmation depends on this field too
});
confirm.addEventListener('input', checkMatch);
checkPassword();
checkMatch();
</script>
</body>
</html>Three details matter here.
passwordcallscheckMatch()on every input. If the user fixes the password after typing the confirmation, the confirmation's error must be re-evaluated, or it would be stale.- The initial calls at the bottom set the starting state. An empty password has no digit, so the field begins in a custom error state. Because the field is also
required, the browser reportsvalueMissingfirst in most cases. Your message appears once the field has a value. - Each rule sets the error on the field the user should fix. The mismatch message belongs on
confirm, notpassword.
Replacing built-in messages
You can also use setCustomValidity to replace the browser's wording for a built-in constraint. Built-in constraints keep their own flags in validity, and those flags are independent of customError. So you can clear your message, read the built-in flags, and set a message that matches.
const username = document.getElementById('username');
function describeUsername() {
username.setCustomValidity(''); // clear first, so built-in flags are judged alone
const v = username.validity;
if (v.valueMissing) {
username.setCustomValidity('Choose a username.');
} else if (v.tooShort) {
username.setCustomValidity('Use at least 3 characters.');
} else if (v.patternMismatch) {
username.setCustomValidity('Use lowercase letters, digits, and underscores only.');
}
}
username.addEventListener('input', describeUsername);
describeUsername();Clearing first is the important step. If you skipped it, customError from the previous pass would still be set. You would then be overwriting your own message instead of reading the browser's verdict. The built-in flags are not affected by customError, so they remain accurate either way.
The flags you can map to messages are these.
| Flag | True when |
|---|---|
| `valueMissing` | A `required` field is empty |
| `typeMismatch` | The value does not fit `type="email"` or `type="url"` |
| `patternMismatch` | The value does not match `pattern` |
| `tooShort` | The value is shorter than `minlength` |
| `tooLong` | The value is longer than `maxlength` |
| `rangeUnderflow` | A number or date is below `min` |
| `rangeOverflow` | A number or date is above `max` |
| `stepMismatch` | The value does not fit `step` |
| `badInput` | The user typed something the browser cannot convert, such as text in a number field |
| `customError` | You set a non-empty message with `setCustomValidity` |
Choosing when to show the message
Setting a message changes state but does not show it. You have three options for display.
- Do nothing more. The browser shows the message in its own bubble when the user submits.
- Call
field.reportValidity()in ablurorchangehandler to show the bubble sooner. It also returnstrueorfalse. - Turn off the bubbles with
form.noValidate = trueand renderfield.validationMessageinto your own error element. The previous chapters covered this pattern. The message you set withsetCustomValidityflows through unchanged.
Be careful with reportValidity() inside an input handler. It moves focus to the field and opens the bubble on every keystroke, which is disruptive. Use input to update state and blur or submit to report it.
Rules the attributes cannot express
Use setCustomValidity when the rule depends on logic, not just on a single constraint. Typical cases:
- A value must differ from another field, or equal it.
- A date range, where the end must come after the start.
- A checkbox group where at least one box must be ticked. A single
requiredcheckbox demands that box specifically, so the group needs custom logic. - A value that must pass a checksum or a lookup.
The checkbox group is a good example of putting the error on one control.
const boxes = document.querySelectorAll('input[name="topic"]');
function checkTopics() {
const any = Array.from(boxes).some((box) => box.checked);
boxes[0].setCustomValidity(any ? '' : 'Pick at least one topic.');
}
boxes.forEach((box) => box.addEventListener('change', checkTopics));
checkTopics();Only the first box carries the error. That is enough to block submission, and it gives the browser one place to focus and report. Cross-field rules like this get fuller treatment in a later chapter.
Gotchas
- Controls that do not validate. Disabled controls,
readonlyinputs,type="hidden"and controls insidedatalisthavewillValidateset tofalse. A custom error on them is ignored when the form is submitted. CheckwillValidatewhen a rule seems to have no effect. - Non-string arguments. The argument is converted to a string. Passing
undefinedproduces the text "undefined" as a message, andnullbecomes "null". Always pass''to clear. - Messages and locale. The browser's built-in messages follow the user's language. Strings you set do not. If your site is localized, translate your own messages.
- Pattern messages. For
pattern, thetitleattribute is usually appended to the browser's message. If you replace the message withsetCustomValidity, you control the whole text and thetitleno longer matters to the bubble. Keeptitlefor assistive technology anyway. - Asynchronous results. If a rule depends on a network call, the response may arrive after the user has changed the value. Set the error only if the value the request checked still equals the current one. Otherwise a stale result can block a now-correct field. This chapter's rules are all synchronous, and async checks have their own chapter.
Summary of the working model
setCustomValidity(text)setscustomErrorand makesvalidationMessagereturn your text.setCustomValidity('')is the only way to clear it.- Recompute on every event that can change the answer, including events on other fields that the rule depends on.
- Clear before reading built-in flags if you are rewording built-in messages.
- Display is a separate step: the browser's bubble,
reportValidity(), or your own error elements.
Exercise
A user types "abc" into a confirmation field that must match the password "abc1". Your script calls confirm.setCustomValidity('Passwords do not match.') in an input listener on confirm only. The user then corrects the password field to "abc" and the confirmation field still blocks submission. What went wrong, and how do you fix it?
Show answer
The confirmation's error is only re-evaluated when the confirmation field itself changes. Changing the password does not run checkMatch, so the old message stays set. Fix it by also calling checkMatch from an input listener on the password field, so the empty string is set once the values match.
Exercise
You write username.setCustomValidity('Use lowercase letters only.') inside an if (username.validity.patternMismatch) block, and you never call setCustomValidity('') anywhere. After the user fixes the value, the form still cannot be submitted. Why, and what is the minimal fix?
Show answer
The custom error is not cleared by the browser, so customError stays true and validity.valid stays false. Call username.setCustomValidity('') at the start of the handler, before reading validity.patternMismatch, so each pass starts clean and sets a message only when the rule fails.