Prashobh Prashobh - 6 months ago 76
Javascript Question

Javascript Regex for any one mandatory special character

I have created a regex for password validation

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&#^~|_.`+=-])[A-Za-z\d$@$!%*?&#^~|_.`+=-]{12,25}/



  • Allows minimum 12 and maximum 25 characters.

  • Must have at least one number.

  • One upper case

  • One lowercase

  • One special character.(Any one)



It is working fine.

But I need to mention mandatory fields for special characters
[$@$!%*?&#^~|_.`+=-]
, is there any way I can create a regex which can be treated any special character. For example Pras022222()1 this wont treat as valid password since I didn't mention () this in the list.

Answer Source

You may use this regex with \W:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\W]).{12,25}$

RegEx Demo

Here character class [_\W] will enforce presence of any non-word character or a underscore.

RegEx Breakup:

  • ^: Assert start
  • (?=.*[a-z]): Assert that we have a lowercase letter ahead
  • (?=.*[A-Z]): Assert that we have a uppercase letter ahead
  • (?=.*\d): Assert that we have a digit ahead
  • (?=.*[_\W]): Assert that we have a underscore or a non-word character ahead
  • .{12,25}: Match a string with 12 to 25 characters
  • $: Assert end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download