1

how can i not allow these chars:

\ / " ' [ ] { } | ~ ` ^ &

using javascript regular expression pattern?

Devin Burke
  • 13,642
  • 12
  • 55
  • 82
franbm
  • 19
  • 1
  • possible duplicate of http://stackoverflow.com/questions/705672/regular-expression-to-allow-a-set-of-characters-and-disallow-others – outis Apr 03 '10 at 09:36
  • Also: http://stackoverflow.com/questions/756567/regular-expression-for-excluding-special-characters, http://stackoverflow.com/questions/1152844/regex-for-alphanumeric-and-the-character, http://stackoverflow.com/questions/1763071/negate-characters-in-regular-expression, http://stackoverflow.com/questions/834002/regular-expression-that-includes-all-keyboard-characters-except-and, ... – outis Apr 03 '10 at 09:44
  • And (despite PHP tags): http://stackoverflow.com/questions/1778958/php-regular-expression-accept-selected-characters-only, http://stackoverflow.com/questions/878715/checking-string-for-illegal-characters-using-regular-expression. – outis Apr 03 '10 at 09:46
  • 1
    What do you need it for? It looks like some sort of security instalment, but anything you do in JavaScript can be overridden by a malicious user. Also, in general, it is a lot easier to avoid injection holes by specifying a list of allowed characters, that way you are also safe from anything you hadn't thought about. – aaaaaaaaaaaa Apr 03 '10 at 11:50

3 Answers3

1

Check a string contains one of these characters:

if(str.match(/[\\\/"'\[\]{}|~`^&]/)){
  alert('not valid');
}

Validate a whole string, start to end:

if(str.match(/^[^\\\/"'\[\]{}|~`^&]*$/)){
  alert('it is ok.');
}
Kobi
  • 135,331
  • 41
  • 252
  • 292
0

To specifically exclude just those characters (Just prefix with backslash)

const isNotSpecial = /[^\\\/\"\'\[\]\{\}\|\~\`\^\&]/.test(myvalue);

To generally exclude all special characters

const isNotSpecial = /[^\W]/.test(myvalue);
Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
-2

Another solution is encoding these special characters into the regular expression format.

Using package regexp-coder

const { RegExpCoder } = require('regexp-coder');

console.log(RegExpCoder.encodeRegExp('a^\\.()[]?+*|$z'));
// Output: 'a\^\\\.\(\)\[\]\?\+\*\|\$z'