表單驗證做得早一點,後端就能少收一堆垃圾資料。以下整理常見的輸入限制寫法,從「只能中文」到「IP 位址格式」都有。
<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
onbeforepaste="clipboardData.setData('text',
clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))">
\u4E00-\u9FA5 是 CJK 基本區的範圍,方括號前加 ^ 表示「除了這些之外都清掉」。onbeforepaste 則攔住貼上時的內容。
<input onkeyup="value=value.replace(/[^\d]/g,'')"
onbeforepaste="clipboardData.setData('text',
clipboardData.getData('text').replace(/[^\d]/g,''))">
更簡潔的寫法是用 \D(非數字的反義集合):
<input onkeyup="this.value=this.value.replace(/\D/g,'')"
onafterpaste="this.value=this.value.replace(/\D/g,'')">
上半句管鍵盤輸入,下半句管貼上。
<input type="text" style="ime-mode:disabled">
onkeyup="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'')"
<input type="text" id="aa1" onkeyup="this.value=this.value.replace(/[^\d&:]/g,'')" onblur="this.value=this.value.replace(/[^\d&:]/g,'')" onafterpaste="this.value=this.value.replace(/[^\d&:]/g,'')"/>
<input type="text" id="aa" onkeyup="value=value.replace(/[^\w&=]|_/ig,'')" onblur="value=value.replace(/[^\w&=]|_/ig,'')" />
function isregname(checkobj)
{
var checkOK = "0123456789-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var checkStr = checkobj;
var allValid = true;
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
}
return (allValid);
}
搭配表單提交前的檢查:
if(!(isregname(obj.loginname.value))){
alert("[會員代號]不符合規範,會員代號只能是英文字母或數字");
obj.loginname.focus();
return(false);
}
if(!(isregname(obj.password.value))){
alert("[密碼]不符合規範,密碼只能是英文字母或數字");
obj.password.focus();
return(false);
}
<script language="javascript" event="onkeydown" for="document">
if(event.srcElement.name == 'TextBox1')
{
if(!KeyIsNumber(event.keyCode))
{
return false; // 這句話最關鍵
}
}
</script>
<script language="javascript">
function KeyIsNumber(KeyCode)
{
// 0-9 之間,或者 backspace(8)、DEL(46)
if(((KeyCode > 47) && (KeyCode < 58)) || (KeyCode == 8) || (KeyCode == 46))
{
return true;
}
else
{
return false;
}
}
</script>
把 IP 拆成四格輸入框,每填滿三位或超出範圍就自動跳到下一格,左右鍵也能在格子間移動:
<HTML>
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=gb2312">
<style>
.a3{width:30;border:0;text-align:center}
</style>
<script>
function mask(obj){
obj.value = obj.value.replace(/[^\d]/g,'')
key1 = event.keyCode
if (key1 == 37 || key1 == 39) // 左右鍵切格
{
obj.blur();
nextip = parseInt(obj.name.substr(2,1))
nextip = key1 == 37 ? nextip - 1 : nextip + 1;
nextip = nextip >= 5 ? 1 : nextip
nextip = nextip <= 0 ? 4 : nextip
eval("ip" + nextip + ".focus()")
}
if(obj.value.length >= 3)
if(parseInt(obj.value) >= 256 || parseInt(obj.value) <= 0)
{
alert(parseInt(obj.value) + " IP地址錯誤!")
obj.value = ""
obj.focus()
return false;
}
else
{
obj.blur();
nextip = parseInt(obj.name.substr(2,1)) + 1
nextip = nextip >= 5 ? 1 : nextip
nextip = nextip <= 0 ? 4 : nextip
eval("ip" + nextip + ".focus()")
}
}
function mask_c(obj)
{
clipboardData.setData('text', clipboardData.getData('text').replace(/[^\d]/g,''))
}
</script>
<title>IP地址輸入</title>
</head>
<body>IP地址輸入
<div style="border-width:1;border-color:black;border-style:solid;width:165;font-size:9pt">
<input type="text" name="ip1" maxlength="3" class="a3" onkeyup="mask(this)" onbeforepaste="mask_c()">.
<input type="text" name="ip2" maxlength="3" class="a3" onkeyup="mask(this)" onbeforepaste="mask_c()">.
<input type="text" name="ip3" maxlength="3" class="a3" onkeyup="mask(this)" onbeforepaste="mask_c()">.
<input type="text" name="ip4" maxlength="3" class="a3" onkeyup="mask(this)" onbeforepaste="mask_c()">
</div>
</body>
</HTML>
這些技巧都源自 IE 時代,onbeforepaste、clipboardData、ime-mode、event 全域物件在標準瀏覽器裡並不存在,今天要跨瀏覽器就得改用 input 事件搭配 clipboardData/document.execCommand('paste') 之外的方案,或直接改用 HTML5 的型別限制:
<input type="number" min="0" max="255" step="1"> <input type="text" pattern="[0-9]*" inputmode="numeric"> <input type="text" maxlength="3" pattern="\d*">
更重要的觀念是:前端限制只是使用者體驗,不是安全性。任何繞過方式(關 JS、直接打 API、改 DevTools)都能突破,所以伺服器端一定要再驗證一次型別、範圍與格式。另外 eval("ip"+n+".focus()") 這種動態呼叫,改成陣列存 DOM 會安全又清楚。