SriHarish
SriHarish

Reputation: 311

Capture Backslash in Javascript

Am using Jquery validator to create a rule to disallow spl characters in fields.

jQuery.validator.addMethod("noSpecialChar", function(value,element) {
    if(value.match(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/)){
      return false;
    }else{
      return true;
    }
  }, "No Special Charaters are allowed.");

the regular expression am using is not capturing "\" backslash.

can some one please help me on this?

Upvotes: 0

Views: 180

Answers (2)

MikeM
MikeM

Reputation: 13631

The backslash \ is the escape character so to include a literal backslash in a regular expression (or string) you must escape the backslash character itself, i.e. \\.

In your character class the single \ is being used to escape the ] to prevent it from being interpreted as the metacharacter which closes the character class.

The other \ in your character class are unnecessary as the ] is the only metacharacter that needs to be escaped within it.
], \, ^ and - are the only characters that may need to be escaped in a character class.

As already mentioned, you may be better to specify what characters are disallowed by looking for characters that are not within a specified group, e.g.

/[^a-z\d\s]/i

which disallows any characters not a-z, A-Z, 0-9 or whitespace (the \d is short for 0-9 and the i means case-insensitive).

Also, in place of the if-else statement and match, you could simply use

return !value.test( /[^a-z\d\s]/i )

although you may find it less readable (the ! inverts the boolean result of the test call).

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

You need to include the backslash in the character class:

if(value.match(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/\\]/))

But what about other "special characters" like §? The list is nearly endless - perhaps you would rather like to exclude all characters except for A-Za-z0-9_:

if (value.match(/\W/))

Upvotes: 3

Related Questions