jQuery method to validate a password with specific

2019-09-07 04:12发布

I'm new to jquery and trying to use the validate a password of pretty basic complexity.

The password must be at least 7 characters, have at least 1 upper case, have at least 1 lower case, and at least 1 number OR special character.

This question is very similar to this answer I found, however I'm having trouble adding the "digit OR special char" part.

I think it's a regex I'm just not getting. My modification to that answer looks like this:

$.validator.addMethod("pwcheck", function(value) {
return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
   && /[a-z]/.test(value) // has a lowercase letter
   && /[A-Z]/.test(value) //has an uppercase letter
   && (/\d/.test(value) || /~!@#$%^&*_-+=[]\{}|;':",.<> /.test(value)
       // has a digit or special char
});

2条回答
Anthone
2楼-- · 2019-09-07 04:32

EDIT: The following answer is for the original version of the OP.


Assuming your regex is correct, you have a syntax error.

This line...

&& (/\d/.test(value) || /~!@#$%^&*_-+=[]\{}|;':",.<> /.test(value)

should be...

&& /\d/.test(value) || /~!@#$%^&*_-+=[]\{}|;':",.<> /.test(value)

or

&& (/\d/.test(value) || /~!@#$%^&*_-+=[]\{}|;':",.<> /.test(value))
查看更多
成全新的幸福
3楼-- · 2019-09-07 04:52

You needed to close your parenthesis on your last conditional. But I actually noticed a couple issues with your regex. For one, you need to group all the special characters in a bracket, so it won't match all those characters consecutively.

But beyond that, the Regex is way too verbose. Here's a much simpler solution.

$.validator.addMethod("pwcheck", function(value) {
    return /[A-Z]+[a-z]+[\d\W]+/.test(value)
});

This will match 1 or more uppercase characters, 1 or more lowercase characters and 1 or more digit/special character. There's one flaw with this however. It will only match in this particular order. That means the uppercase must come before the lowercase and the lowercase before the digits. It will match things like

AFDSabcd1435

but not things like

aA5fdHD14z

To have a more accurate validation, it should probably look more like this

$.validator.addMethod("pwcheck", function(value) {
    return /[A-Z]+/.test(value) && /[a-z]+/.test(value) && 
    /[\d\W]+/.test(value) && /\S{7,}/.test(value);
});

This isn't quite as clean as my previous idea, but it will pass more options.

Here's an example you can test out with a JavaScript function.

function testValue(string) { 
    return /[A-Z]+/.test(string) && /[a-z]+/.test(string) &&
    /[\d\W]/.test(string) && /\S{7,}/.test(string)
}

testValue("aGFbsdf4")
=> true
查看更多
登录 后发表回答