879

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Swapnil Tatkondawar
  • 8,947
  • 3
  • 13
  • 3
  • See [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/48346033#48346033) – ctwheels Jan 14 '21 at 15:04

43 Answers43

2220

Minimum eight characters, at least one letter and one number:

"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"

Minimum eight characters, at least one letter, one number and one special character:

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$"

Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"

Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"

Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,10}$"
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Srinivas
  • 22,589
  • 1
  • 14
  • 4
  • 97
    "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$" does not allow symbols as one of the 8 characters – Wee Jan 06 '15 at 02:30
  • 37
    I found the following allowed for all characters (special & punctuation), without making them mandatory: "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d\w\W]{8,}$" – Gavin Jun 06 '20 at 21:00
  • @Gavin With this regex the string "DdBxgyZv2FBaa" is valid but should not detected as valid, because there is no special character. – Maisen1886 Jun 13 '22 at 12:20
  • 1
    Note that those regular expressions above do not cover symbols like `^`, `(` and `)`. An alternative would be: `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,}$` which covers all other characters. – kataba Aug 24 '22 at 13:22
  • 6
    An alternative for checking symbol should be `(?=.*[^\w\d\s])` in which it tries to have a negative match that isn't a word, digit, and whitespace. The current one only catches specific symbols `[A-Za-z\d@$!%*?&]` in which common symbols like dot(.) or plus(+) will fail – crrmacarse Nov 02 '22 at 20:14
  • `*` matches 0 or more characters. Why not use `+`? Then how does the regex make sure there is at least 1 such character? – Atharva Karandikar Jan 30 '23 at 11:35
  • I'm not a regex pro by any means, but why the need to repeat the character checks? If you were simply looking to check if the password met the criteria, couldn't you simplify to the following? `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,10}$` or in my case i switch to allow more broader set of symbols `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d\s]).{8,10}$` Also, no one should ever limit their password length to 10. – loesak Apr 01 '23 at 02:17
  • One major problem I found in this solution is, if the password contains a special character that is not specified in the regular expression (e.g, comma), it fails. – Tharaka Apr 13 '23 at 14:37
  • for TypeScript regex should not be in a string it must be as: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/ covered by '/'. – Sheikh Wahab Mahmood Jun 27 '23 at 03:29
  • "Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character" - not working for fF3 fdsfdsfd4f!j#. Looks like it doesn't allow the '#', but it's not mentioned in the quoted definition. – Rony Tesler Jul 19 '23 at 22:53
781

You may use this regex with multiple lookahead assertions (conditions):

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$

This regex will enforce these rules:

  • At least one upper case English letter, (?=.*?[A-Z])
  • At least one lower case English letter, (?=.*?[a-z])
  • At least one digit, (?=.*?[0-9])
  • At least one special character, (?=.*?[#?!@$%^&*-])
  • Minimum eight in length .{8,} (with the anchors)
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    It may be worth removing "&" from allowed special characters, due to ampersand character codes. There are a few ASCII characters that don't behave normally in JavaScript strings and that is one of them. – dat1dev Aug 19 '23 at 22:15
133

Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...

But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords:

Anything with less than eight characters OR anything with no numbers OR anything with no uppercase OR or anything with no lowercase OR anything with no special characters.

So:

^(.{0,7}|[^0-9]*|[^A-Z]*|[^a-z]*|[a-zA-Z0-9]*)$

If anything matches that, then it's an invalid password.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • 7
    This is one of the better answers. Other answers don't include special characters like "(" or ")". Great solution! – G M Jul 06 '22 at 02:44
  • This is nice, thank you! I have noticed that some browsers like Firefox create "safe passwords" without special characters, so I removed the last alternative |[a-zA-Z0-9]* .. I'm fine with that. – NinoMarconi Jul 27 '22 at 06:54
  • 3
    Additionally, some browser regex engines don't allow lookahead assertions, so this is an ideal solution if needing client-side validation. – djoll Nov 06 '22 at 02:15
  • this looks really good, I was looking for an answer along this lines but is this performant? – Barreto May 21 '23 at 17:20
  • Yes, it should perform much better than the lookahead-based options. – Matt Timmermans May 21 '23 at 18:11
  • The only answer that makes sense and doesn't use lookaheads. It's much cleaner and simpler – Nikola Diklich Jul 19 '23 at 23:18
58

Use the following Regex to satisfy the below conditions:

Conditions:

  1. Min 1 uppercase letter.
  2. Min 1 lowercase letter.
  3. Min 1 special character.
  4. Min 1 number.
  5. Min 8 characters.
  6. Max 30 characters.

Regex:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{8,30}$/
Saikat
  • 14,222
  • 20
  • 104
  • 125
SHASHANK HONRAO
  • 581
  • 4
  • 3
  • 4
    In which way is your answer better than the the other answers written years ago? – JSantos Jul 13 '17 at 12:46
  • 3
    @SHASHANKHONRAO I updated the expression to: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&+~`|{}:;<>/])[A-Za-z\d$@$!%*?&+~`|{}:;<>/]{8,15} which will include the following Nonalphanumeric characters: (@$!%*?&+~`|{}:;<>/) – JoshYates1980 Oct 23 '17 at 12:58
53

Just a small improvement for @anubhava's answer: Since special character are limited to the ones in the keyboard, use this for any special character:

^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$

This regex will enforce these rules:

  • At least one upper case English letter
  • At least one lower case English letter
  • At least one digit
  • At least one special character
  • Minimum eight in length
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Edwin Beltran
  • 4,419
  • 4
  • 20
  • 16
  • 2
    In the JavaScript flavor, `\W` matches only ASCII characters. So you haven't changed that, and now you have to filter out whitespace characters. Furthermore, all the parentheses and `{1,}` quantifiers you added are pure noise, and removing the non-greedy (`?`) operators was pointless. There is no improvement here. – Alan Moore Nov 08 '15 at 06:00
49

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...

  • at least 8 characters
  • at least 1 numeric character
  • at least 1 lowercase letter
  • at least 1 uppercase letter
  • at least 1 special character

/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}$/

JSFiddle Link - simple demo covering various cases

scniro
  • 16,844
  • 8
  • 62
  • 106
  • 2
    Nice one. but have found one issue that your regular expression will not accept _(underscore) as a special character :( . – user3217843 May 20 '16 at 05:08
  • 8
    I really like this answer except that it can't accept underscores. All I did was replace `(?=.*?[^\w\s])` with `(?=.*?([^\w\s]|[_]))` to add support for underscores and it works great now. Also @Dinish.net the system I use trims the whitespace out of the password string when we get it, so using vanilla JS [String.prototype.trim()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) method would work well if you want to use this answer. – Devin Carpenter Aug 27 '19 at 01:38
46

 

✅ The following 4 regex patterns can help you to write almost any password validation

 

 

Pattern 1:

 

Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, one special character, no space, and it must be 8-16 characters long.

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\W)(?!.* ).{8,16}$/

 

Explanation:

 

  • (?=.*[0-9]) means that the password must contain a single digit from 1 to 9.

 

  • (?=.*[a-z]) means that the password must contain one lowercase letter.

 

  • (?=.*[A-Z]) means that the password must contain one uppercase letter.

 

  • (?=.*\W) means that the password must contain one special character.

 

  • .{8,16} means that the password must be 8-16 characters long. We must use this at the end of the regex, just before the $ symbol.

 

What are ^ and $:

 

^ indicates the beginning of the string. $ indicates the end of the string.

If we don't use these ^ & $, the regex will not be able to determine the maximum length of the password. In the above example, we have a condition that the password can't be longer than 16 characters, to make that condition work, we have used these ^ & $

 

Remove maximum length restriction:

 

  • Instead of .{8,16}, if we used .{8,}, it would mean that the password must be at least 8 characters long. So, there will not be any condition for checking the maximum length of the password.

 

Don't accept any number(digit):

 

  • Instead of (?=.*[0-9]), if we used (?!.*[0-9]), it would mean that the password must not contain any digit from 1-9 (Difference with the (?=.*[0-9]) is the use of ! instead of =)

 

Don't accept any spcecial character:

 

  • Instead of (?=.*\W), if we used (?!.*\W), it would mean that the password must not contain any special characters (The difference with the (?=.*\W) is the use of ! instead of =)

 

Alternative Syntax for number(digit):

 

  • Instead of (?=.*[0-9]), we could have used (?=.*\d). (?=.*\d) also means that the password must contain a single digit from 1 to 9.

 

 

Pattern 2:

 

Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, one underscore but no other special character, no space and it must be 8-16 characters long.

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*_)(?!.*\W)(?!.* ).{8,16}$/

 

Difference with the Pattern 1

 

  • Here, we have used (?=.*_) which wasn't on the Pattern 1.

 

  • (?=.*_)(?!.*\W) means that the password must contain an underscore but can not contain any other special character.

 

Pattern 3:

 

Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, one underscore, no space and it must be 8-16 characters long. Usage of any other special character other than underscore is optional.

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*_)(?!.* ).{8,16}$/

 

Difference with the Pattern 2

 

  • Here, we have not used (?!.*\W) what was on the Pattern 2.

 

  • But it still has the (?=.*_)

 

  • By just removing the (?!.*\W), special characters have become optional. Now, one underscore is required but any other special character can be used or not as it's optional.

 

Pattern 4:

 

Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, and one underscore, and it must be 8-16 characters long. Usage of any other special character and usage of space is optional.

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,16}$/

 

Difference with the Pattern 3

 

  • Here, we have not used (?=.*_) & (?!.* ) which was on the Pattern 3.

 

  • By removing (?=.*_), it's no longer mandatory to pass one underscore. Now, passing special characters is optional.

 

  • By removing the (?!.* ), usage of space has become optional too.
Rasaf Ibrahim
  • 1,737
  • 14
  • 10
  • Tried with `Java` says that `Qwezxc123@` is not valid `Pattern.compile("/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\\W)(?!.* ).{8,16}\$/")` – user924 Sep 01 '23 at 11:46
23

A more "generic" version(?), allowing none English letters as special characters.

^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$

var pwdList = [
    '@@V4-\3Z`zTzM{>k',
    '12qw!"QW12',
    '123qweASD!"#',
    '1qA!"#$%&',
    'Günther32',
    '123456789',
    'qweASD123',
    'qweqQWEQWEqw',
    '12qwAS!'
  ],
  re = /^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$/;
  
  pwdList.forEach(function (pw) {
    document.write('<span style="color:'+ (re.test(pw) ? 'green':'red') + '">' + pw + '</span><br/>');
  });
SamWhan
  • 8,296
  • 1
  • 18
  • 45
14

Import the JavaScript file jquery.validate.min.js.

You can use this method:

$.validator.addMethod("pwcheck", function (value) {
    return /[\@\#\$\%\^\&\*\(\)\_\+\!]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[A-Z]/.test(value)
});
  1. At least one upper case English letter
  2. At least one lower case English letter
  3. At least one digit
  4. At least one special character
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikram
  • 710
  • 8
  • 12
14

For standard password requirements I found this to be useful:

  • At least 1 alphabet

  • At least 1 digit

  • Contains no space

  • Optional special characters e.g. @$!%*#?&^_-

  • Minimum 8 characters long

    /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&^_-]{8,}$/

You can also set the upper limit for example {8,32} up to 32 characters long.

Sazzad
  • 176
  • 1
  • 9
12

Try this one:

  1. Minimum six characters
  2. At least one uppercase character
  3. At least one lowercase character
  4. At least one special character

Expression:

"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.]{6, 20}/"

Optional Special Characters:

  1. At least one special character
  2. At least one number
  3. Special characters are optional
  4. Minimum six characters and maximum 16 characters

Expression:

"/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/"

If the min and max condition is not required then remove .{6, 16}

  • 6 is minimum character limit
  • 20 is maximum character limit
  • ?= means match expression
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ojus kulkarni
  • 1,877
  • 3
  • 25
  • 41
12

This worked for me:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&])([a-zA-Z0-9@$!%*?&]{8,})$
  • At least 8 characters long;
  • One lowercase, one uppercase, one number and one special character;
  • No whitespaces.
Dana
  • 151
  • 1
  • 7
11

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:

def validatePassword(password: String): Boolean = {
  if (password.length < 8)
    return false

  var lower = false
  var upper = false
  var numbers = false
  var special = false

  password.foreach { c =>
    if (c.isDigit)       numbers = true
    else if (c.isLower)  lower = true
    else if (c.isUpper)  upper = true
    else                 special = true
  }

  lower && upper && numbers && special
}
  • You solution is much better than regex. I know you answer is old but Thank you for a great creative solution. – Marco Dec 11 '22 at 19:20
11

What about considering the following regex solution:

^(?=.*[\w])(?=.*[\W])[\w\W]{8,}$

Which validates the following:

  1. At least one lowercase
  2. At least one uppercase
  3. At least one digit
  4. At least one special character
  5. At least it should have 8 characters long.

Check it out working at the following link https://regex101.com/r/qPmC06/4/

  • Your suggested regex and the one under the regex101 link varies. Shouldn't it be `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W\_])[A-Za-z\d\W\_]{8,}$`? – CraZ Dec 17 '19 at 17:07
11

For a more strict validation where the following is required:

  1. At least One Upper Case Character
  2. At least one Lower Case character
  3. At least one digit
  4. At least one symbol/special character @$!%*#?&^_-
  5. Minimum 8 characters/digits

Regex:

/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*#?&^_-]).{8,}/

I hope it helps someone with a more stringent.

Steve Johnson
  • 3,054
  • 7
  • 46
  • 71
10
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+,.\\\/;':"-]).{8,}$
    
Milan Paudyal
  • 519
  • 9
  • 11
8

Another option is to make use of contrast in the lookahead assertions using a negated character class, optionally matching any character except that is listed before matching the character that should be matched.

^(?=[^A-Z\n]*[A-Z])(?=[^a-z\n]*[a-z])(?=[^0-9\n]*[0-9])(?=[^#?!@$%^&*\n-]*[#?!@$%^&*-]).{8,}$

See a regex demo

In parts, the pattern matches:

  • ^ Start of string
  • (?=[^A-Z\n]*[A-Z]) Positive lookahead, assert 0+ times any char except A-Z or a newline. Then match a char A-Z
  • (?=[^a-z\n]*[a-z]) The same approach for a char a-z
  • (?=[^0-9\n]*[0-9]) The same approach for a digit 0-9
  • (?=[^#?!@$%^&*\n-]*[#?!@$%^&*-]) The same approach for a char that you would consider special
  • .{8,} Match 8 or more times any character except a newline
  • $ End of string

Notes

  • A dot can also match a space. If you do not want to allow matching a space, then .{8,} can be changed to \S{8,} to match 8 or more non whitespace characters
  • Using either . or \S can match more characters than are specified in the lookahead assertions. If you only want to match the characters that are used in the assertions, you can change .{8,} to match only the allowed characters [#?!@$%^&*A-Za-z0-9-]{8,} using a character class

const regex = /^(?=[^A-Z\n]*[A-Z])(?=[^a-z\n]*[a-z])(?=[^0-9\n]*[0-9])(?=[^#?!@$%^&*\n-]*[#?!@$%^&*-]).{8,}$/;
[
  "abcA1#!A",
  "#!asdfSFD1;",
  "# a f F1 ;",
  "1111111111",
  "aaaaaaaa",
  "11111111",
  "AAAAAAAA",
  "########",
  "aA1#"
].forEach(s =>
  console.log(regex.test(s) ? `Match --> ${s}` : `No match --> ${s}`)
);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    Noticeably efficient, nice one! For those who like any special and no whitespace, a variation can be to use `(?=[^\W_]*[\W_])` for special-part together with replacing the dot-part at end to `\S{8,}` ([demo](https://regex101.com/r/nQfS6q/1)) – bobble bubble Sep 26 '22 at 19:40
5
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/

this the simple way to use it while validate atleast 1 uppercase 1 lowercase and 1 number

and this is the example while I use in express validation

check('password')
    .notEmpty()
    .withMessage('Password cannot be null')
    .bail()
    .isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters')
    .bail()
    .matches(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/)
    .withMessage(
      'Must have atleast 1 uppercase, 1 lowercase letter and 1 number'
    ),
Hasan Tezcan
  • 1,116
  • 1
  • 11
  • 23
4

Testing this one in 2020:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Verify yourself

const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
const str = `some12*Nuts`;
let m;

if ((m = regex.exec(str)) !== null) {
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
MiKr13
  • 1,297
  • 13
  • 20
4

Keep it simple stupid:

This should do the trick for you, always.

Regex: ^(.{0,7}|[^a-z]{1,}|[^A-Z]{1,}|[^\d]{1,}|[^\W]{1,})$|[\s]

If your password matches the regex above, it is invalid.

If there's no match, your password is valid and contains has at least 8 characters, one upper case letter, one lower case letter and one symbol or special character. And it also contains no spaces, tabs or line breaks.

Breakdown of Regex

  1. .{0,7} - matches if password has between 0 to 7 characters.
  2. [^a-z]{1,} - matches if no lower case is found
  3. [^A-Z]{1,} - matches if no upper case is found
  4. [^\d]{1,} - matches if no number (between [0-9]) is found
  5. [\s] - matches if a white space, tab or line break is found.

With this approach there's no limit or restriction in terms of symbols allowed. If you want to limit to few symbols allowable, just change [^\W] with [^YourSymbols].

Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24
3

@ClasG has already suggested:

^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$

but it does not accept _(underscore) as a special character (eg. Aa12345_).

An improved one is:

^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*([^\w\s]|[_]))\S{8,}$
SONewbiee
  • 363
  • 2
  • 15
3

I've found many problems here, so I made my own.

Here it is in all it's glory, with tests:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^a-zA-Z\d\s])).{9,}$

https://regex101.com/r/DCRR65/4/tests

Things to look out for:

  1. doesn't use \w because that includes _, which I'm testing for.
  2. I've had lots of troubles matching symbols, without matching the end of the line.
  3. Doesn't specify symbols specifically, this is also because different locales may have different symbols on their keyboards that they may want to use.
Stefano
  • 1,686
  • 1
  • 16
  • 25
3

Demo:

function password_check() {
  pass = document.getElementById("password").value;
  console.log(pass);
  regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
  if (regex.exec(pass) == null) {
    alert('invalid password!')
  }
  else {
    console.log("valid");
  }
}
<input type="text" id="password" value="Sample@1">
<input type="button" id="submit" onclick="password_check()" value="submit">
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
3
var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");

Best For javascript

Masoud
  • 332
  • 2
  • 9
3

I would use:

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[\W_]).{8,}$

Most of the answers assume that you use one of their predefined special characters, but I would say it is better, if any special character can be used, if it is not a-zA-Z0-9, so you could write: [^a-zA-Z0-9], but it is shorter to use "Not Word": \W which is equivalent to: [^a-zA-Z0-9_] - but of course you want the underscore _ to be seen as special char, so simple add it, then you end with: [\W_]

A very nice and helpful tool to build your personal regex, modify or test existing ones is regex101: https://regex101.com

Stuepfnick
  • 71
  • 5
2
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+-]).{6}
Mike G
  • 4,232
  • 9
  • 40
  • 66
shiyani suresh
  • 778
  • 12
  • 12
2

According to your need this pattern should work just fine. Try this,

^(?=(.*\d){1})(.*\S)(?=.*[a-zA-Z\S])[0-9a-zA-Z\S]{8,}

Just create a string variable, assign the pattern, and create a boolean method which returns true if the pattern is correct, else false.

Sample:

String pattern = "^(?=(.*\d){1})(.*\S)(?=.*[a-zA-Z\S])[0-9a-zA-Z\S]{8,}";
String password_string = "Type the password here"

private boolean isValidPassword(String password_string) {
    return password_string.matches(Constants.passwordPattern);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

If you do not like to use regex. So this module helps a lot: https://www.npmjs.com/package/password-validator

var passwordValidator = require('password-validator');
 
// Create a schema
var schema = new passwordValidator();
 
// Add properties to it
schema
.is().min(8)                                    // Minimum length 8
.is().max(100)                                  // Maximum length 100
.has().uppercase()                              // Must have uppercase letters
.has().lowercase()                              // Must have lowercase letters
.has().digits(2)                                // Must have at least 2 digits
.has().not().spaces()                           // Should not have spaces
.is().not().oneOf(['Passw0rd', 'Password123']); // Blacklist these values
 
// Validate against a password string
console.log(schema.validate('validPASS123'));
// => true
console.log(schema.validate('invalidPASS'));
// => false
nakorndev
  • 803
  • 2
  • 11
  • 18
2

With this regex all conditions are met:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^A-Za-z0-9]).{8,}$

This regex will enforce these rules:

  • At least one upper case, (?=.*?[A-Z])
  • At least one lower case, (?=.*?[a-z])
  • At least one digit, (?=.*?[0-9])
  • At least one special character, that is any character not included on the first 3 conditions, (?=.*?[^A-Za-z0-9])
  • Minimum eight in length .{8,}
2

This is what worked for me:

(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[@$!%*#?~(&)+=^_-]).{8,}
Raj
  • 385
  • 2
  • 15
1

Pattern to match at least 1 upper case character, 1 digit and any special characters and the length between 8 to 63.

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d\\W]{8,63}$"

This pattern was used for JAVA programming.

HK boy
  • 1,398
  • 11
  • 17
  • 25
Anup Seth
  • 31
  • 5
1

Use the following Regex to satisfy the below conditions:

Conditions: 1] Min 1 special character.
            2] Min 1 number.
            3] Min 8 characters or More

Regex: ^(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{8,}$

Can Test Online: https://regex101.com

Samrat Saha
  • 585
  • 1
  • 7
  • 18
1

Just we can do this by using HTML5.

Use below code in pattern attribute,

pattern="(?=^.{8,}$)((?=.*\d)(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"

It will work perfectly.

Vidya
  • 63
  • 2
  • 10
1

You can use the below regular expression pattern to check the password whether it matches your expectations or not.

((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*()]).{8,20})
Harshal_Kalavadiya
  • 312
  • 1
  • 5
  • 15
1
(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$

Link check online https://regex101.com/r/mqGurh/1

Tai Ho
  • 546
  • 4
  • 9
1

I've actually just copied the first answer here and turned it into a more ux-convenient regex which needs one upper, one lower and at least 8 chars but accepts everything "in between".

This one is an example-regex which requires

  1. at least 8 characters length
  2. at least one lowercase letter
  3. at least one uppercase letter

IMPORTANT: This regex will also except all other characters e.g. numbers, special characters like $,#,! etc. - as long as the rules 1. to 3. match the input string

^(?=.*[a-z])(?=.*[A-Z]).{8,}$

Mind the "." alomst at the end of the regex. This will match almost any (and afaik any readable) character

Frithjof Schaefer
  • 1,135
  • 11
  • 22
1

Use this,

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%?=*&]).{8,20})

It will validate for at least one lowercase, one upper case, one number and the special charecters of (!,@,#,$,%,?,=,*,&).

Minimum length is 8 and maximum length is 20

Anand Raja
  • 2,676
  • 1
  • 30
  • 35
0

In Java/Android, to test a password with at least one number, one letter, one special character in following pattern:

"^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,}$"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dadaji
  • 43
  • 6
0

Try this:

^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$

This regular expression works for me perfectly.

function myFunction() {
    var str = "c1TTTTaTTT@";
    var patt = new RegExp("^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$");
    var res = patt.test(str);
    console.log("Is regular matches:", res);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kiwi Rupela
  • 2,238
  • 5
  • 24
  • 44
0

Hope the below works. I tried this in Azure custom policy.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&amp;*\-_+=[\]{}|\\:',?/`~&quot;();!])([A-Za-z\d@#$%^&amp;*\-_+=[\]{}|\\:',?/`~&quot;();!]|\.(?!@)){6,16}$
HK boy
  • 1,398
  • 11
  • 17
  • 25
Venkatesh
  • 269
  • 1
  • 11
0
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\\`~!@#$%^&/*()_+=[{}]\\[\\]|\\:;'\"<>.,?/-]).{8,}$";
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
-1

A solution I found in one of the previous answer as:

*Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}"*

...didn't work for me, but the following is a simplified version and works great (add any special character you like, I added # here), and add the number rule as you do with the letters as:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&]){8,}"
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
Carette
  • 11
  • 1
-2
     var value=$("#password").val();
     $.validator.addMethod("strongePassword",function(value) 
     {
         return /^[A-Za-z0-9!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]*$/.test(value) && /[a-z]/.test(value) && /\d/.test(value) && /[A-Z]/.test(value)&& /[A-Z]/.test(value);`enter code here`
     },'Password must have minimum 9 characters and contain at least 1 UPPERCASE, 1 lower case, 1 number, 1 special character.');
Wprog_dy
  • 67
  • 5