示例工程 45-web-component-forms
45-web-component-forms/demo-02-validation/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>校验与禁用演示</title>
<style>
body { margin: 0; padding: 32px; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.7; }
.box { max-width: 720px; margin-bottom: 16px; padding: 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
h1 { margin: 0 0 16px; font-size: 28px; }
h2 { margin: 0 0 8px; font-size: 17px; }
p { margin: 0 0 10px; color: #334155; }
form { display: grid; gap: 10px; max-width: 360px; }
label.for { display: block; font-size: 14px; font-weight: 600; }
x-code { display: block; }
.row { display: flex; align-items: center; gap: 8px; font-size: 14px; }
button { padding: 6px 12px; border: 1px solid #2563eb; border-radius: 6px; background: #2563eb; color: #fff; font: inherit; font-size: 13px; }
code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
#out { margin: 0; color: #14532d; font-size: 14px; }
#out[data-state="error"] { color: #b91c1c; }
</style>
</head>
<body>
<h1>校验与禁用</h1>
<div class="box">
<h2>格式校验</h2>
<p>邀请码格式为 <code>ABC-123</code>。空值与格式错误都会阻止提交。</p>
<form id="f">
<fieldset id="fs">
<legend>邀请信息</legend>
<div>
<label class="for" for="code">邀请码</label>
<x-code id="code" name="code" value="" required pattern="[A-Z]{3}-\d{3}"></x-code>
</div>
</fieldset>
<div class="row">
<button type="submit">提交</button>
<span id="out" role="status"></span>
</div>
<label class="row"><input type="checkbox" id="disable" /> 禁用整个 fieldset</label>
</form>
</div>
<div class="box">
<h2>说明</h2>
<p><code>setValidity</code> 的锚点让浏览器把错误气泡指向内部输入框。</p>
<p>禁用由 <code>formDisabledCallback</code> 同步到内部控件。</p>
</div>
<script>
class XCode extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["value", "disabled"];
constructor() {
super();
this.internals = this.attachInternals();
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
:host { display: block; }
input { width: 100%; padding: 7px 9px; border: 1px solid #cbd5e1; border-radius: 6px; font: inherit; text-transform: uppercase; }
input:focus { outline: 2px solid #2563eb; outline-offset: 1px; }
.msg { display: block; margin-top: 4px; color: #b91c1c; font-size: 13px; }
.msg:empty { display: none; }
</style>
<input part="input" aria-label="邀请码,格式 ABC-123" autocomplete="off" />
<span class="msg" part="message" role="alert"></span>
`;
this.input = root.querySelector("input");
this.msg = root.querySelector(".msg");
this.input.addEventListener("input", () => {
this.setAttribute("value", this.input.value);
this.validate();
});
}
connectedCallback() {
this.input.value = this.getAttribute("value") ?? "";
this.validate();
}
attributeChangedCallback(name, oldValue, newValue) {
if (!this.isConnected) return;
if (name === "value" && this.input.value !== (newValue ?? "")) this.input.value = newValue ?? "";
if (name === "disabled") this.input.disabled = this.hasAttribute("disabled");
this.validate();
}
validate() {
const value = this.input.value.trim();
const required = this.hasAttribute("required");
const pattern = this.getAttribute("pattern");
let flags = {};
let message = "";
if (required && !value) {
flags = { valueMissing: true };
message = "请填写邀请码";
} else if (pattern && value && !new RegExp("^(?:" + pattern + ")$").test(value)) {
flags = { patternMismatch: true };
message = "格式应为 ABC-123";
}
this.internals.setValidity(flags, message, this.input);
this.internals.setFormValue(value || null);
this.input.setAttribute("aria-invalid", String(Boolean(message)));
this.input.setAttribute("aria-describedby", message ? "code-msg" : "");
this.msg.id = "code-msg";
this.msg.textContent = message;
}
formResetCallback() {
this.input.value = this.getAttribute("value") ?? "";
this.validate();
}
formDisabledCallback(disabled) {
this.input.disabled = disabled;
}
}
customElements.define("x-code", XCode);
const form = document.getElementById("f");
const out = document.getElementById("out");
form.addEventListener("submit", (event) => {
event.preventDefault();
out.dataset.state = "ok";
out.textContent = "已提交:code=" + new FormData(form).get("code");
});
form.addEventListener("invalid", (event) => {
out.dataset.state = "error";
out.textContent = "校验失败:" + (event.target.getAttribute("name") ?? event.target.tagName);
}, true);
document.getElementById("disable").addEventListener("change", (event) => {
document.getElementById("fs").toggleAttribute("disabled", event.target.checked);
});
</script>
</body>
</html>