2013-05-28 53 views
3

如何禁用在文本框中粘貼特殊字符?如何禁用在文本框中粘貼特殊字符

進出口使用關於onkeypress事件的事件處理程序

function disableOtherChar(evt) { 
    var charCode; 
    charCode = (evt.which) ? evt.which : evt.keyCode; 
    var ctrl; 
    ctrl = (document.all) ? event.ctrlKey : evt.modifiers & Event.CONTROL_MASK; 
    if ((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 9 || charCode == 45 || (ctrl && charCode == 86) || ctrl && charCode == 67) { 
     return true; 
    } else { 
     $(":text").live("cut copy paste", function (e) { 
      e.preventDefault(); 
     }); 
     return false; 
    } 
} 

但它不阻止粘貼時,只有在輸入特殊字符,

+0

嘗試處理'onpaste'事件以及 –

+0

我試過,但它不起作用 – JeAr

+1

什麼都行不通 - 你能詳細說明一下嗎?與一次處理一個字符的按鍵不同 - 使用onpaste,您將必須使用已經有無效字符的完整字符串,只需將其刪除即可 –

回答

8

假設你有一個輸入

<input id="textInput" name="textInput"> 

,你有下面的腳本來驗證副本:

$(function(){ 

    $("#textInput").bind('paste',function() 
    { 
     setTimeout(function() 
     { 
      //get the value of the input text 
      var data= $('#textInput').val() ; 
      //replace the special characters to '' 
      var dataFull = data.replace(/[^\w\s]/gi, ''); 
      //set the new value of the input text without special characters 
      $('#textInput').val(dataFull); 
     }); 

    }); 
}); 
0

不是一個答案,只是評論:

var ctrl; 
ctrl = (document.all) ? event.ctrlKey:evt.modifiers & Event.CONTROL_MASK; 

請學習使用特徵檢測,推斷基於對象推理的行爲註定至少會在某些時候失敗。

此外,不要使用密鑰代碼,測試實際字符。 E.g如果你只是想允許字母,數字和其他幾個人:

function hasInvalidChars(s) { 

    // allow letters, spaces, numbers only 
    var validChars = /[\w\s\d]/gi; 
    var x = s.replace(validChars, ''); 
    return !!x.length; 
} 

alert(hasInvalidChars('asdf1234 1234asd')); // false 
alert(hasInvalidChars('asdf1.234 1234asd')); // true 

展開一系列以任何你想要有效的字符。

哦,如果你想把它當作一個班輪:

function hasInvalidChars(s) { 
    return !!s.replace(/[\w\s\d]/gi, '').length; 
} 
0

您可以使用第三方插件,如jquery.alphanum,它也適用於粘貼(ctrl + v)。 的代碼看起來是這樣的:

$("input").alphanum();

或者你可以在這樣一個更spceficied方式來使用它:

$("#elemet").alphanum({ 
    allow  : "asd", 
    disallow : "[email protected]#", 
    allowUpper : false 
}); 

你需要將它添加到您的JQuery聲明上面的代碼。

我提的是,你還可以修改從腳本jquery.alphanum.js上線124,你會發現一個函數名getBlacklistAscii黑名單陣列,在您修改var blacklist = ...什麼適合你。