最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Block special characters but allow spaces - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 5

Can'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">

发布评论

评论列表(0)

  1. 暂无评论