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.

JavascriptForm Validation

Code

javascriptsnippet
18 lines
// 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.
  • document exist 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

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.