即時過濾寫法
$('#mobile-vcode').on('keyup change', function(){
this.value = this.value.replace(/\D/g, ''); // 移除非數字
if (this.value.length === 4) {
// 驗證碼長度達標,可觸發 AJAX 驗證
// verifyCode(this.value);
}
});
原生 HTML5 替代
<input type="text" id="mobile-vcode" inputmode="numeric" pattern="\d*" maxlength="4">
inputmode="numeric":行動裝置喚起數字鍵盤。
pattern="\d*":表單驗證規則。
maxlength:原生長度限制。
完整表單範例
<form id="verifyForm">
<input type="text" id="mobile-vcode" name="vcode" maxlength="4" inputmode="numeric" pattern="\d*" required>
<button type="submit" id="btnSubmit" disabled>驗證</button>
</form>
<script>
$('#mobile-vcode').on('input', function(){
this.value = this.value.replace(/\D/g, '');
$('#btnSubmit').prop('disabled', this.value.length !== 4);
});
$('#verifyForm').on('submit', function(e){
e.preventDefault();
$.post('/api/verify', {code: $('#mobile-vcode').val()}, function(res){
if (res.ok) location.href = '/success';
else alert('驗證碼錯誤');
});
});
</script>
注意
- 使用
input 事件而非 keyup,可攔截貼上、拖曳、輸入法組合字。
- 前端過濾僅為 UX,**伺服端必須再次驗證**。
- 若需支援負數/小數,調整正則:
/[^\d.-]/g 並控制小數點/負號出現次數。