SetCustomValidity Custom Form Feedback

Attach per-field messages with setCustomValidity, clear them with an empty string to restore built-in checks, and arbitrate submission with checkValidity.

TypescriptForm Validation

Code

typescriptsnippet
26 lines
const form = document.querySelector<HTMLFormElement>('#signup');
const username = form?.querySelector<HTMLInputElement>('[name="username"]');

function validateUsername(input: HTMLInputElement): void {
  if (input.value.trim().length < 3) {
    // 非空自定义消息:字段进入 :invalid,提交被浏览器拦截
    input.setCustomValidity('用户名至少 3 个字符');
  } else if (!/^[a-z0-9_]+$/i.test(input.value)) {
    input.setCustomValidity('只允许字母、数字和下划线');
  } else {
    input.setCustomValidity(''); // 空字符串清除自定义规则,恢复内建校验
  }
}

form?.addEventListener('submit', (event) => {
  if (username) validateUsername(username);
  // checkValidity 统一裁决:不通过则阻止默认提交并聚焦第一个无效字段
  if (!form.checkValidity()) {
    event.preventDefault();
    const firstInvalid = form.querySelector<HTMLInputElement>(':invalid');
    console.log('blocked:', firstInvalid?.validationMessage);
  }
});

// 编程式触发同一套 UI 反馈(消息横幅 + 焦点),返回布尔值
console.log('reportValidity:', username?.reportValidity() ?? 'no input mounted');

The message cycle

validateUsername sets a non-empty message for a too-short or illegal username (the field enters :invalid and blocks submission), and clears it with setCustomValidity(‘’) when the value passes — an empty string hands control back to the built-in checks.

Submission arbitration

The submit listener first guards with if (username) before calling validateUsername — the optional-chained query may be null, and the guard keeps the sample compiling under strict mode. form.checkValidity() then decides: on failure it preventDefaults and prints blocked: with the first :invalid field’s validationMessage.

Programmatic feedback

username?.reportValidity() shows the same message banner and focus behavior on demand and returns whether the field is valid; the demo prints it (or no input mounted when the input is absent).

Interactive Tools for This Topic

FAQ

Why does the listener guard with if (username) before validating?
username comes from form?.querySelector and is HTMLInputElement | null | undefined; the guard keeps the call type-safe under strict mode, matching the runtime fact that the listener only attaches when the form exists.
What does setCustomValidity('') do?
It clears the custom rule, restoring the built-in constraint checks for the field — non-empty messages mark the field invalid and block submission.