Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex to check that user input does not consist of special characters only?

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.

like image 803
Arko Avatar asked Sep 06 '10 06:09

Arko


People also ask

How do you find special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do I check if a string has special characters?

To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


2 Answers

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.

like image 139
Yanick Rochon Avatar answered Sep 25 '22 17:09

Yanick Rochon


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.

like image 36
Tim Pietzcker Avatar answered Sep 26 '22 17:09

Tim Pietzcker