setCustomValidity Rewrites Validation Messages
setCustomValidity attaches a custom message that fails validity until cleared with an empty string, covering rules the built-in constraints cannot express.
Code
// setCustomValidity 写入自定义校验消息;传空字符串 = 恢复"有效"
const form = document.createElement('form');
const password = Object.assign(document.createElement('input'), { type: 'password', value: 'hunter2' });
const confirm = Object.assign(document.createElement('input'), { type: 'password', value: 'hunter3' });
form.append(password, confirm);
document.body.append(form);
function syncValidity() {
// 两次输入一致才算有效;不一致时把原因挂到 confirm 上
confirm.setCustomValidity(confirm.value === password.value ? '' : 'Passwords do not match');
console.log(confirm.checkValidity(), JSON.stringify(confirm.validationMessage));
}
syncValidity(); // 一致之前始终无效,validationMessage 带着原因
confirm.addEventListener('input', syncValidity);
confirm.value = 'hunter2';
syncValidity(); // 现在通过:消息回到空串,表单可以提交setCustomValidity Rewrites Validation Messages, line by line
All of the logic lives in the function syncValidity.
What to watch for
- Ready as-is on a bare install of the language.
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Applying it
Central definition: function syncValidity()
Statements that matter
confirm.addEventListener('input', syncValidity);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does setCustomValidity Rewrites Validation Messages run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.