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.)
Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.
Yes, also your regex will match if there are just spaces. My reply was to Neha choudary's comment. @Pierre Three years later -- I came across this question today, saw your comment; I use regex hero (regexhero.net) for testing regular expressions.
The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.
The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.
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]+$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With