0

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?

2
  • 1
    Instead of excluding all special characters this way, you could just allow alphanumeric characters? [0-9a-zA-Z]? Commented Jan 29, 2013 at 7:07
  • 1
    add `\\` to the regexp characters Commented Jan 29, 2013 at 7:07

2 Answers 2

3

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/))
Sign up to request clarification or add additional context in comments.

1 Comment

only a few set of spl characters are required to exclude... Thanks for the help.... :)
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.