Search code examples
javascriptregexregex-negation

regex to restrict special characters except few


I was able to write a regex to validate the below criterias for an input box.

  1. contain minimum of 14 characters
  2. contain at least 1 capital letter (A-Z)
  3. contain at least 1 simple letter (a-z)
  4. contain at least 1 number (0-9)
  5. contain at least 1 special symbol (+=!@#$%^&*)

Regex -> ^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[+=!@#$%^&*])(?=\\S+$).{14,}$

However, this regex allows other special characters which are not mentioned. I want to restrict all the special characters except these +=!@#$%^&*

could someone help me to modify the given regex with the above criteria?


Solution

  • Instead of . that allows any character you can use a character set to restrict the allowed characters to a specific set:

    ^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[+=!@#$%^&*])(?=\\S+$)[0-9A-Za-z+=!@#$%^&*]{14,}$