[英]javascript regex to disallow all special characters
Here is a fiddle to start - http://jsfiddle.net/zuVpx/1/这是一个开始的小提琴 - http://jsfiddle.net/zuVpx/1/
Javascript code: Javascript代码:
<script>
function validate(e) {
var regex = new RegExp("[a-zA-Z0-9]");
var key = e.keyCode || e.which;
key = String.fromCharCode(key);
if(!regex.test(key)) {
e.returnValue = false;
if(e.preventDefault) {
e.preventDefault();
}
}
}
</script>
HTML code: HTML代码:
<input type="text" onkeypress="validate(event)" />
I want only characters and numbers.我只想要字符和数字。 Keys like backspace, delete, capslock and arrowkeys etc should work.
退格键、删除键、大写锁定键和箭头键等键应该可以工作。
Thanks in advance.提前致谢。
Try尝试
/[-!$%^&*()_+|~=`\\#{}\[\]:";'<>?,.\/]/.test(your_variable)
It returns true if there is a match.如果匹配,则返回 true。
How about just using an additional if clause?只使用一个额外的 if 子句怎么样? Something like...
就像是...
key.charCodeAt(0) > 32
So...所以...
function validate(e) {
var regex = new RegExp("[a-zA-Z0-9]");
var key = e.keyCode || e.which;
key = String.fromCharCode(key);
if(!regex.test(key) && key.charCodeAt(0) > 32) {
e.returnValue = false;
if(e.preventDefault) {
e.preventDefault();
}
}
}
To overcome the problem that for example the left arrow key produces the same key
value as the %
key, you could use要克服,例如左箭头键产生相同的问题
key
值作为%
键,你可以使用
function validate(e) {
e = e || window.event;
var bad = /[^\sa-z\d]/i,
key = String.fromCharCode( e.keyCode || e.which );
if ( e.which !== 0 && e.charCode !== 0 && bad.test(key) ) {
e.returnValue = false;
if ( e.preventDefault ) {
e.preventDefault();
}
}
}
Any printable character should produce a non-zero e.which
and e.charCode
value.任何可打印的字符都应该产生一个非零的
e.which
和e.charCode
值。
See JavaScript Madness: Keyboard Events .请参阅JavaScript 疯狂:键盘事件。
The above assumes spaces are valid - if not, just remove the \\s
from the negated character class.以上假设空格有效 - 如果不是,只需从否定字符类中删除
\\s
。
This Worked for Me.这对我有用。 Prevent Users from Entering Special Characters(Except Backspace etc)
防止用户输入特殊字符(退格等除外)
PatternValidation(e){
if(!e.key.match(/^[a-zA-Z0-9]*$/))
{
e.preventDefault();
}
},
This is triggered through binding html attribute with keydown event handler这是通过将 html 属性与 keydown 事件处理程序绑定来触发的
<input type="text" onkeydown="PatternValidation($event)">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.