admin 管理员组

文章数量: 1086019

I have to do jQuery form validation for password.

The password should contain at least two special characters in any order. I have tried with Regular Expression for password validation but it does not address that two random special characters can e at any order.

How do I do it using a JavaScript regular expression?

I have to do jQuery form validation for password.

The password should contain at least two special characters in any order. I have tried with Regular Expression for password validation but it does not address that two random special characters can e at any order.

How do I do it using a JavaScript regular expression?

Share Improve this question edited May 23, 2017 at 11:51 CommunityBot 11 silver badge asked Jun 4, 2015 at 15:59 Nasif Md. TanjimNasif Md. Tanjim 3,9825 gold badges29 silver badges40 bronze badges 1
  • At least two special characters and at least one numeric character: /^(?=.*\d)(?=(.*[`!@#$%\^&*\-_=\+'/\.,]){2})(?!.*\s).{6,15}$/ – Nasif Md. Tanjim Commented Jun 4, 2015 at 18:05
Add a ment  | 

3 Answers 3

Reset to default 6

You do not have to use look-arounds in cases when you do not have to.

If you only need to make sure the string has at least 2 characters of a specific set, use this kind of a regex (with a negated class to make it more robust):

/(?:[^`!@#$%^&*\-_=+'\/.,]*[`!@#$%^&*\-_=+'\/.,]){2}/

See demo

In javascript it worked for me:

/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]){2})/
var goodtogo = false;
var pass = 'simp!le@';   //example
var times = pass.match(/[\\\[\]\/\(\)\+\*\?`!@#$%\^&_=-]/g).length;
if(times >= 2)
    goodtogo = true;

Now I advice you to try several passwords and if you find a bug or something don't hesitate to yell back.

And if you have more special chars just add them to the parameter for match.

Hope it helps.

本文标签: javascriptRegular expression to match at least two special characters in any orderStack Overflow