I just answered another Regex question here.
jQuery method to validate a password with specific rules
The objective is to create a regex that takes the following
- 1 or more uppercase characters
- 1 or more lowercase characters
- 1 digit or special character - i.e.
!@#$%^&*()-=
, etc. - Length has to be at least 7 characters
I found a nifty solution for the special characters with \W
that matches non-word characters. That should match the special characters.
But I was wondering if this solution could be dried up to not require multiple conditionals. My original solution was in one line
$.validator.addMethod("pwcheck", function(value) {
return /[A-Z]+[a-z]+[\d\W]+/.test(value)
});
This matches the first three conditions but there was one problem. It only matches in that exact order. That means the lowercase must follow the uppercase and so on. While examples like this passed
AGHjfd8437
Others failed like this
agTF8djRd4
I had to modify my solution to pass tests like this. This is what I came up with.
$.validator.addMethod("pwcheck", function(value) {
return /[A-Z]+/.test(value) && /[a-z]+/.test(value) &&
/[\d\W]+/.test(value) && /\S{7,}/.test(value);
});
But I was wondering if this could be combined to just one Regex. And if so, would it be cleaner looking than the second?