I want a regular expression to check that:
A password contains at least eight characters, including at least one number and includes both lower and uppercase letters and special characters, for example #
, ?
, !
.
It cannot be your old password or contain your username, "password"
, or "websitename"
And here is my validation expression which is for eight characters including one uppercase letter, one lowercase letter, and one number or special character.
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"
How can I write it for a password must be eight characters including one uppercase letter, one special character and alphanumeric characters?
Not directly answering the question, but does it really have to be a regex?
I used to do lots of Perl, and got used to solving problems with regexes. However, when they get more complicated with all the look-aheads and other quirks, you need to write dozens of unit tests to kill all those little bugs.
Furthermore, a regex is typically a few times slower than an imperative or a functional solution.
For example, the following (not very FP) Scala function solves the original question about three times faster than the regex of the most popular answer. What it does is also so clear that you don't need a unit test at all:
In Java/Android, to test a password with at least one number, one letter, one special character in following pattern:
Try this one:
Expression:
Optional Special Characters:
Expression:
If the min and max condition is not required then remove
.{6, 16}
I had some difficulty following the most popular answer for my circumstances. For example, my validation was failing with characters such as
;
or[
. I was not interested in white-listing my special characters, so I instead leveraged[^\w\s]
as a test - simply put - match non word characters (including numeric) and non white space characters. To summarize, here is what worked for me...8
characters1
numeric character1
lowercase letter1
uppercase letter1
special characterJSFiddle Link - simple demo covering various cases
@ClasG has already suggested:
but it does not accept _(underscore) as a special character (eg. Aa12345_).
An improved one is: