Regular expression to match at least two special c

2020-02-07 10:52发布

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?

3条回答
beautiful°
2楼-- · 2020-02-07 11:26

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-07 11:27

In javascript it worked for me:

/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]){2})/
查看更多
We Are One
4楼-- · 2020-02-07 11:44
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.

查看更多
登录 后发表回答