2

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;
  }
  });
zer0
  • 4,657
  • 7
  • 28
  • 49

3 Answers3

1

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">
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Why not use a regex to allow only alphabets,numbers and spaces(if required) ^[A-Za-z0-9 ]*$

now30
  • 40
  • 6
  • You are right. I was using `/^[A-z]/` earlier but it allowed some special characters, so I completely abandoned it.. but your modification seems simpler. – zer0 Jul 09 '17 at 20:29
  • 1
    @ultimatecoder: That is most probably because [`[A-z]` matches more than just letters](http://stackoverflow.com/a/29771926/3832970). Also, `^[A-Za-z0-9 ]*$` won't allow `я`, `ź`, etc. That seems to be out of scope of the current question. – Wiktor Stribiżew Jul 09 '17 at 20:34
0

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

stomtech
  • 454
  • 4
  • 10