Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"
The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.
I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password
) which should improve user experience.
From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.
Seeing your comment, this is how I would go about it:
Must be eight characters Long: You do not need a regex for this. Using the
.Length
property should be enough.Including one uppercase letter: You can use the
[A-Z]+
regular expression. If the string contains at least one upper case letter, this regular expression will yieldtrue
.One special character: You can use either the
\W
which will match any character which is not a letter or a number or else, you can use something like so[!@#]
to specify a custom list of special characters. Note though that characters such as$
,^
,(
and)
are special characters in the regular expression language, so they need to be escaped like so:\$
. So in short, you might use the\W
.Alphanumeric characters: Using the
\w+
should match any letter and number and underscore.
Take a look at this tutorial for more information.
( # Start of group
(?=.*\d) # must contain at least one digit
(?=.*[A-Z]) # must contain at least one uppercase character
(?=.*\W) # must contain at least one special symbol
. # match anything with previous condition checking
{8,8} # length is exactly 8 characters
) # End of group
In one line:
((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})
Edit 2019-05-28:
You need to match entire input string. So, you can enclose the regex between ^
and $
to prevent accidentally assuming partial matches as matching entire input:
^((?=.*\d)(?=.*[A-Z])(?=.*\W).{8,8})$
Sources:
Password matching expression
Password Strength Validation with Regular Expressions