$("#mytextbox").on("keypress", function(event) {
// Disallow anything not matching the regex pattern (A to Z uppercase, a to z lowercase, digits 0 to 9 and white space)
// For more on JavaScript Regular Expressions, look here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
var englishAlphabetDigitsAndWhiteSpace = /[A-Za-z0-9 ]/g;
// Retrieving the key from the char code passed in event.which
// For more info on even.which, look here: http://stackoverflow.com/q/3050984/114029
var key = String.fromCharCode(event.which);
//alert(event.keyCode);
// For the keyCodes, look here: http://stackoverflow.com/a/3781360/114029
// keyCode == 8 is backspace
// keyCode == 37 is left arrow
// keyCode == 39 is right arrow
// englishAlphabetDigitsAndWhiteSpace.test(key) does the matching, that is, test the key just typed against the regex pattern
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetDigitsAndWhiteSpace.test(key)) {
return true;
}
// If we got this far, just return false because a disallowed key was typed.
return false;
});
$('#mytextbox').on("paste",function(e)
{
e.preventDefault();
});
function ValidateKey()
{
var key=window.event.keyCode;
var allowed='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ :;,.?!£$%^&*()_+-*{}@~<>&"\'';
return allowed.indexOf(String.fromCharCode(key)) !=-1 ;
}
5条答案
按热度按时间czfnxgou1#
您可以尝试以下使用JavaScript replace method的代码。replace方法接受一个正则表达式模式,所以你可以定义几乎任何你想/不想在文本框中输入的东西:
下面是jsFiddle来尝试一下:http://jsfiddle.net/leniel/rtE54/
经过一番思考,我实现了以下代码:
你可以在这里阅读更多:JavaScript regex + jQuery to allow only English chars/letters in input textbox
7uhlpewt2#
您可以根据
onkeypress
检查密钥是否在您设置的限制内来限制密钥。你可以把它当作
关于Fiddle:http://jsfiddle.net/UHGRz/3/
你可以用jQuery应用于所有的输入控件。没有工作与复制/粘贴,有你需要的Lenier解决方案与替换.
和一个转换为jQuery代码
关于Fiddle:http://jsfiddle.net/UHGRz/5/
jckbn6z73#
如果Cher是charger,则可以这样做
你可以用阿拉伯字符做同样的比较
以unicode表示
vu8f3i0k4#
试试这样的东西。英语字符的正则表达式为/^[A-Za-z 0 -9]*$/
6fe3ivhb5#
对于电子邮件,仅允许英语字符:(Vuejs)
输入
粘贴