6

How to put a validation over a field which wouldn't allow only special characters, that means AB#,A89@,@#ASD is allowed but @#$^& or # is not allowed. I need the RegEx for this validation.

Arko
  • 108
  • 1
  • 1
  • 8
  • 2
    this has nothing to do with jQuery, you mean javascript ? – Yanick Rochon Sep 06 '10 at 06:59
  • 5
    Nono... JavaScript has been renamed to jQuery, didntchya know? – mpen Sep 06 '10 at 07:50
  • @OP: You might want to take a look at http://bassistance.de/jquery-plugins/jquery-plugin-validation/ and http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation – mpen Sep 06 '10 at 07:51

3 Answers3

10
str.match(/^[A-Z#@,]+$/)

will match a string that...

  • ... starts ^ and ends $ with the enclosed pattern
  • ... contains any upper case letters A-Z (will not match lower case letters)
  • ... contains only the special chars #, @, and ,
  • ... has at least 1 character (no empty string)

For case insensitive, you can add i at the end : (i.g. /pattern/i)

** UPDATE **

If you need to validate if the field contains only specials characters, you can check if the string contains only characters that are not words or numbers :

if (str.match(/^[^A-Z0-9]*$/i)) {
   alert('Invalid');
} else {
   alert('Valid');
}

This will match a string which contains only non-alphanumeric characters. An empty string will also yield invalid. Replace * with + to allow empty strings to be valid.

Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • i think i did'nt make you understand,point is there are too many of special characters & what i wrote earlier are just the instances["AB#,A89@,@#ASD is allowed but @#$^& or # is not allowed"].It can be of any combination like A*B,AB*,*Ab but there should'nt be only special characters.The only way to use special character on that particular field is to associate the special charater with either Digit[e.g-9()] or with any character.whta to do?? – Arko Sep 06 '10 at 07:14
2

If you can use a "negative match" for your validation, i. e. the input is OK if the regex does not match, then I suggest

^\W*$

This will match a string that consists only of non-word characters (or the empty string).

If you need a positive match, then use

^\W*\w.*$

This will match if there is at least one alphanumeric character in the string.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

I believe what you're looking for is something like this:

!str.match(/^[@#$^&]*$/)

Checks that the string does not contain only symbols, i.e., it contains at least one character that isn't a symbol.

mpen
  • 272,448
  • 266
  • 850
  • 1,236