原程式碼用 onkeypress 驗證,無法捕捉中文輸入法組合字、貼上、拖拽、退格等操作。
oninput<input type="text" id="username" maxlength="12" placeholder="5-10 位英數" oninput="validate(this)" />
<span id="msg"></span>
<script>
function validate(el) {
const v = el.value;
const msg = document.getElementById('msg');
if (!v) { msg.textContent = '請輸入用戶名'; msg.style.color = 'red'; return; }
if (!/^[A-Za-z0-9]{5,10}$/.test(v)) {
msg.textContent = '僅限 5-10 位英數字元';
msg.style.color = 'red';
} else {
msg.textContent = '格式正確';
msg.style.color = 'green';
}
}
</script>
form.addEventListener('submit', e => {
if (!/^[A-Za-z0-9]{5,10}$/.test(username.value)) {
e.preventDefault();
alert('用戶名格式錯誤');
}
});
核心:**oninput + 正則** 覆蓋所有輸入方式,比 onkeypress/keydown/keyup 可靠得多。