表單驗證固然重要,但直接從輸入端限制能省下不少來回。以下示範如何讓欄位只接受數字。
$("#money").bind("propertychange",function() {
if(""!=this.value){
var str = this.value.replace(/(^\s*)|(\s*$)/g, "");
if(this.value != str )
this.value = str;
}
if( isNaN(Number(this.value)))
this.value = this.value.replace(/[\D]/,'');
});
這裡把事件綁在 id 為 money 的欄位上:先去掉前後空白,再用 \D 把所有非數字字元清掉。
$("#phone").bind("propertychange", function() {
if(""!=this.value){
var str = this.value.replace(/(^\s*)|(\s*$)/g, "");
if(this.value != str )
this.value = str;
}
if (this.value.indexOf('.') != -1) {
this.value = this.value.replace(/[\.]/, '');
this.focus();
}
if (isNaN(Number(this.value))) {
this.value = ($.trim(this.value)).replace(/[\D]/, '');
this.focus();
}
});
單純攔字元還不夠,使用者仍可能用中文輸入法輸入。透過 CSS 的 ime-mode:disabled 就能關掉輸入法。
建立一個 CSS 類:
.TextBox_NotDragpaste
{
ondragenter:expression(ondragenter=function(){return false;});
onpaste:expression(onpaste=function(){return false;});
}
若還需要禁用中文輸入,多加一行即可:
.TextBox_NotDragpaste
{
ime-mode:disabled;
ondragenter:expression(ondragenter=function(){return false;});
onpaste:expression(onpaste=function(){return false;});
}
提醒兩點:CSS expression 是 IE 專屬語法,且有效能與安全性疑慮,正式環境建議改用 JS 綁定 onpaste 與 ondragenter 事件並 return false;另外 propertychange 同樣是 IE 專屬事件,跨瀏覽器時可改用 input 事件,效果相同而相容性更好。