admin管理员组文章数量:1308325
I need to block the special characters in input, but my code in Chrome does not allow typing space between words, in Firefox works normally.
var regex = new RegExp("^[0-9a-zA-Z\b]+$");
var key = String.fromCharCode(!event.charCode ? event.which: event.charCode);
if (!regex.test(key))
{
event.preventDefault();
return false;
}
I need to block the special characters in input, but my code in Chrome does not allow typing space between words, in Firefox works normally.
var regex = new RegExp("^[0-9a-zA-Z\b]+$");
var key = String.fromCharCode(!event.charCode ? event.which: event.charCode);
if (!regex.test(key))
{
event.preventDefault();
return false;
}
Share
Improve this question
asked Apr 14, 2016 at 13:41
csfcsf
1891 gold badge3 silver badges14 bronze badges
3 Answers
Reset to default 5Can't you just add the space to the RegExp?
Code would bee something like:
var regex = new RegExp("^[0-9a-zA-Z \b]+$");
var key = String.fromCharCode(!event.charCode ? event.which: event.charCode);
if (!regex.test(key))
{
event.preventDefault();
return false;
}
I found this method while trying to take input in a Name field. I wanted to allow alphabets and spaces but not numbers and special characters. Here is what I did.
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode <
123 ) || (charCode > 31 && charCode < 33))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
Space has charCode 32 and I added a condition to allow character with value greater than 31 and less than 33. I tried = and != too but did not help. This code worked fine for me. Happy Coding.
Another approach other than checking each entered value is to check value after entering whole string.
document.getElementById("ok").onclick = function() {
var regex = new RegExp("^[0-9a-zA-Z\b ]+$");
var str = document.getElementById("demo").value;
if (regex.exec(str) == null) {
alert("Not good.");
document.getElementById("demo").value = null;
return false;
} else {
alert("Good");
// Do whatever you want.
}
}
<input type="text" id="demo">
<input type="button" id="ok" value="Validate">
本文标签: javascriptBlock special characters but allow spacesStack Overflow
版权声明:本文标题:javascript - Block special characters but allow spaces - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741840219a2400455.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论