I'm trying to write a regex for an name field and block all special characters
JS Fiddle: /
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;
}
});
I'm trying to write a regex for an name field and block all special characters
JS Fiddle: https://jsfiddle/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;
}
});
Share
Improve this question
asked Jul 9, 2017 at 19:41
zer0zer0
5,0378 gold badges32 silver badges52 bronze badges
4
-
1
Use
var blockSpecialRegex = /[~`!@#$%^&()_={}[\]:;,.<>+\/?-]/;
– Wiktor Stribiżew Commented Jul 9, 2017 at 19:55 -
Thank you, that worked. Any idea why passing it in
new RegExp
fails? – zer0 Commented Jul 9, 2017 at 19:59 - Yes, you did not define a character class, just enumerated the symbols. – Wiktor Stribiżew Commented Jul 9, 2017 at 20:00
-
@ultimatecoder : see my answer why passing it in
new RegExp
fails. – stomtech Commented Jul 9, 2017 at 20:13
3 Answers
Reset to default 1You 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./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text">
Why not use a regex to allow only alphabets,numbers and spaces(if required) ^[A-Za-z0-9 ]*$
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("[~`!@#$%^&()_={}\\[\\]\\:;,\\.\\/<>\\\\*\\-+\\?]");
See RegExp - Javascript