Reputation: 5822
I have this here:
$("#MyInputBox").keypress(function (e) {
if (e.charCode != 0) {
var regex = new RegExp("^[a-zA-Z0-9\-\s]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
});
Problem is, it does not allow me to enter a space. I WANT it to allow a space. Everything else works fine (i.e I can enter numbers, letters, dash... but not a space.)
Upvotes: 8
Views: 33207
Reputation: 117324
You must escape the backslash before the s
var regex = new RegExp("^[a-zA-Z0-9\\-\\s]+$");
or ommit the constructor:
var regex = /^[a-zA-Z0-9\-\s]+$/
Upvotes: 22