Regular expression to match at least two special c

2020-02-07 11:00发布

问题:

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 come at any order.

How do I do it using a JavaScript regular expression?

回答1:

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



回答2:

In javascript it worked for me:

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


回答3:

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.