Reputation: 5017
I'm trying to write a regex for an name field and block all special characters
JS Fiddle: https://jsfiddle.net/69mqhzq6/
However, my code seems to ignore it. Could someone tell what I'm doing wrong?
$('input').on('keypress', function (e) {
var blockSpecialRegex = new RegExp("~`!@#$%^&()_={}\[\]\:;,.\/<>/-+/?");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
console.log(key)
if(blockSpecialRegex.test(key) || $.isNumeric(key)){
e.preventDefault();
return false;
}
});
Upvotes: 2
Views: 12227
Reputation: 40
Why not use a regex to allow only alphabets,numbers and spaces(if required) ^[A-Za-z0-9 ]*$
Upvotes: 1
Reputation: 476
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
So you need to do this:
var blockSpecialRegex = new RegExp("[~`!@#$%^&()_={}\\[\\]\\:;,\\.\\/<>\\\\*\\-+\\?]");
Upvotes: 0
Reputation: 626699
You just enumerated the special chars without creating a character class defined with the help of [...]
.
I suggest using a regex literal with a character class matching any of the symbols defined in it:
var blockSpecialRegex = /[~`!@#$%^&()_={}[\]:;,.<>+\/?-]/;
Note that the -
should be at the start/end of the character class to denote a literal -
symbol. The ]
inside must be escaped, but [
does not have to be escaped. /
must be escaped because it is a regex delimiter symbol.
JS code:
$('input').on('keypress', function (e) {
var blockSpecialRegex = /[~`!@#$%^&()_={}[\]:;,.<>+\/?-]/;
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
console.log(key)
if(blockSpecialRegex.test(key) || $.isNumeric(key)){
e.preventDefault();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text">
Upvotes: 1