Swapnil Tatkondawar
Swapnil Tatkondawar

Reputation: 9407

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

I want a regular expression to check that:

Here is what I had so far. The expression checked if the password has eight characters including one uppercase letter, one lowercase letter, and one number or special character.

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

What's the right expression to cover all the required rules?

Thank you,

Upvotes: 925

Views: 1493696

Answers (30)

rich neadle
rich neadle

Reputation: 383

I am using Python to demonstrate the REGEX example using Python's re regex module to validate the password. :

Included in my solution, inserted in the regex pattern are the the old_password, username, and the word "password" for different letter case variations.

The solution matches with the requirements for the password:

  • contains at least eight characters,
  • including at least one number and
  • includes both lower and uppercase letters and
  • include at least one special characters, #, ?, !.
  • cannot be your old password
  • cannot contain your username, "password", or "websitename"

PYTHON CODE:

import re

old_password = "Matilda#43555"

// # Collect username and password (defaults "matilda55577" and "HelloSunshine!456" respectively):
username = input("Username: ") or "matilda55577"
new_password = input("Password: ") or "HelloSunshine!456"

// # Insert username and password in the regex pattern: 
pattern = f"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#?!#@^*~+])(?!.*[pP][aA][sS][sS][wW][oO][rR][dD])(?!.*\.\w)(?!.*{username})(?!{old_password}$)" + ".{8,}$"
print(pattern)

pattern_re = re.compile(pattern)

for item in test_password_list: 
    print(item, end=": ")
    if pattern_re.match(item) == None:
        print("(---NOT VALID)")
    else:
        print("(---VALID)")

NOTES REGEX PATTERN:

pattern = f"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#?!#@^*~+])(?!.*[pP][aA][sS][sS][wW][oO][rR][dD])(?!.*\.\w)(?!.*{username})(?!{old_password}$)" + ".{8,}$"

ELEMENTS:

  • f("...{username}{password}") In Python, we can use the f-string and {variable_name_here} to enter the username and old_password values in the pattern.

  • ^...$ Pattern must match from beginning ^ to end $.

  • (?=...) Positive lookahead is successful if can match to the right. Will not consume characters.

  • (?!...) Negative lookahead is successful if can NOT match to the right. Will not consume characters.

  • . Dot (.) special character. Matches all characters (except newline character \n unless single line flag is on)

  • .* Matches 0 or more characters, as many as possible to make a match (greedy).

  • \d Matches a number from zero to 9.

  • [...] Character class. Matches any one character listed inside the character class.

  • [a-z] Range of letters FROM a - z TO. Matches one lower case letter.

  • [A-Z] Range of letters FROM A - Z TO. Matches one upper case letter.

  • [#?!#@^*~+] Matches any one character listed in the character class, in this case matches one of "#?!#@^*~+".

PATTERN STATEMENTS:

  • Between the beginning ^ and the end of $ string:

  • From the beginning of the string:

  • (?=.*\d) Lookahead and make sure there is at least one number.

  • (?=.*[a-z]) Lookahead and make sure there is at least one lower case letter.

  • (?=.*[A-Z]) Lookahead and make sure there is at least one upper case letter.

  • (?=.*[#?!#@^*~+]) Lookahead and make sure there is at least one of these characters # ? ! # @ ^ * ~ +.

  • (?!.*[pP][aA][sS][sS][wW][oO][rR][dD]) Negative lookahead to and make sure that the word "password" is not present in any combination of upper and lower case letters.

  • (?!.*\.\w) Negative lookahead to make sure that there are no literal dots/periods (.) followed by a letter (rules out possible email or url)

  • (?!.*{username}) Fill in username. Negative lookahead to make sure that the username is not any part of the string.

  • (?!{old_password}$) Fill in old_password. Negative lookahead to make sure that the new_password does NOT match the old_password exactly. Note $ says it has reached the end of string.

  • .{8,} If all preceding lookaheads match, proceed to capture 8 or more characters. If less than 8 characters. No match, i.e. invalid new password.

  • $ End of string. If you get here, you have a valid password.


REGEX DEMO: https://regex101.com/r/XlyJNL/2


LIST OF TEST PASSWORDS:


test_password_list = [
new_password, 
old_password, 
username,
"Mother#234!",
"aaahelma!345",
"aaahElma!345",
"oldWorld#2222",
"77#elloYello!!!",
"Matilda#43555555",
"111matilda55577OK"
"1123444A!!!!!!!!",
"1123444A!!!!!Park!!",
"aaapasSword123#!KC",
"pASsWORd123#"
"4Matilda#43555234GGG",
"matilda55577!EFR444",
"maTmatilda55577!EFR444",
"hello.www.com.Park1!.com.youtube.com",
"https://stackoverflow.com/question/1234A!",
"ITs!stackoverflow123.com",
"ToSh4!",
"To2!",
"2!sH1",
"[email protected]",
"Matilda#43555",
"Matilda#435555"
]

RESULT:

Username:
Password:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#?!#@^*~+])(?!.*[pP][aA][sS][sS][wW][oO][rR][dD])(?!.*\.\w)(?!.*matilda55577)(?!Matilda#43555$).{8,}$

HelloSunshine!456: (---VALID)
Matilda#43555: (---NOT VALID)
matilda55577: (---NOT VALID)
Mother#234!: (---VALID)
aaahelma!345: (---NOT VALID)
aaahElma!345: (---VALID)
oldWorld#2222: (---VALID)
77#elloYello!!!: (---VALID)
Matilda#43555555: (---VALID)
111matilda55577OK1123444A!!!!!!!!: (---NOT VALID)
1123444A!!!!!Park!!: (---VALID)
aaapasSword123#!KC: (---NOT VALID)
pASsWORd123#4Matilda#43555234GGG: (---NOT VALID)
matilda55577!EFR444: (---NOT VALID)
maTmatilda55577!EFR444: (---NOT VALID)
hello.www.com.Park1!.com.youtube.com: (---NOT VALID)
https://stackoverflow.com/question/1234A!: (---NOT VALID)
ITs!stackoverflow123.com: (---NOT VALID)
ToSh4!: (---NOT VALID)
To2!: (---NOT VALID)
2!sH1: (---NOT VALID)
[email protected]: (---NOT VALID)
Matilda#43555: (---NOT VALID)
Matilda#435555: (---VALID)

Upvotes: 1

user3408541
user3408541

Reputation: 71

I have a couple issues with this question. I strongly believe this validation should be done on the database side. The password should be handed along to an authentication server like Oracle LDAP, and should only receive a success/failure along with possibly an error message from the database which should only be displayed to the user. I say this because any other approach could encourage man in the middle attacks, where the password is stored somewhere in plain text before being sent to the authentication server.

That being said I wrote my code in Perl as sort of a proof of concept. The regular expressions are all basic PCRE or Perl Compatible Regular Expressions. PCRE are kind of a good idea so that you dont have to rewrite all your regular expressions for every different language. PCRE regular expressions are supported in almost every major language and database, and can be easily converted to Javascript using the pcre-to-regexp package from NPM. Because these regular expressions dont use any lookaheads or special syntax that is not supported everywhere, they will likely work in Javascript as is. But the structure of the program is very important to consider here and leads into my last issue.

My last issue is that I think it is a bad idea to try to write all of this in ONE HUGE MONOLITHIC regular expression. This makes the regular expression very long, complicated, convoluted, hard to read, understand, debug, and maintain. This also makes it error prone in ways that are not obvious and difficult to diagnose.

You dont want to just put in a super long, complicated, convoluted regular expression that you dont really understand and just hope it works. Long, huge regular expressions are difficult to debug even for people really good at this sort of thing. This problem is much more manageable if it is broken down into pieces using smaller, much more basic regular expressions for each criteria. Here is the concept code, which can easily be converted to almost any other language.

#!/usr/bin/perl -w

#These are PCRE regular expressions.  You can convert these to 
#javascript regular expressions using the pcre-to-regexp NPM located here
#https://www.npmjs.com/package/pcre-to-regexp

#the syntax on these regular expressions are basic enough that they may  
#not need converting at all and can be used directly


my $containsEightCharactersRegex   = qr/.{8,}/;
my $containsOneNumberRegex         = qr/\d/;
my $containsBothUpperAndLowerRegex = qr/([a-z].*[A-Z])|([A-Z].*[a-z])/;
my $containsSpecialCharactersRegex = qr/[\#\?\!]/; 
my $oldUsername = "OldUsername";
my $containsOldUsernameRegex       = qr/$oldUsername/;
my $websiteName = "WebsiteName";
my $containsOldWebsiteNameRegex    = qr/$websiteName/;
my ($oldPassword, $newPassword)    = ("OldPassword",quotemeta("NewPassword1!")); #quotemeta will make sure all special characters are properly escaped
my $containsOldPasswordRegex       = qr/$oldPassword/;

if( $newPassword !~ $containsEightCharactersRegex )  { die("Password must contain 8 characters"); }
if( $newPassword !~ $containsOneNumberRegex )        { die("Password must contain one number"); }
if( $newPassword !~ $containsBothUpperAndLowerRegex ){ die("Password must contain both Upper and Lower case characters"); }
if( $newPassword !~ $containsSpecialCharactersRegex ){ die("Password must contain one of the following special characters # ? !"); }
if( $newPassword =~ $containsOldUsernameRegex )      { die("Password contains username ($oldUsername)"); }
if( $newPassword =~ $containsOldWebsiteNameRegex )   { die("Password contains website name ($websiteName)"); }
if( $newPassword =~ $containsOldPasswordRegex )      { die("Password contains old password ($oldPassword)"); }

print "$newPassword is valid\n";

These regular expressions are much more manageable, easy to maintain, expand, and if something goes wrong you know exactly where and how. Please consider restructuring your programs to use many smaller more manageable regular expressions instead of ONE HUGE MONOLITHIC regular expression that is much too convoluted to understand and debug.

Good Luck!

Upvotes: 1

Rasaf Ibrahim
Rasaf Ibrahim

Reputation: 2267

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.

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

js /^(?=.*[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.

Upvotes: 67

Raj
Raj

Reputation: 415

This is what worked for me:

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

Upvotes: 5

Stuepfnick
Stuepfnick

Reputation: 79

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

Upvotes: 4

SHASHANK HONRAO
SHASHANK HONRAO

Reputation: 589

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}$/

Upvotes: 58

Rahul Sheth
Rahul Sheth

Reputation: 21

"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\\`~!@#$%^&/*()_+=[{}]\\[\\]|\\:;'\"<>.,?/-]).{8,}$";

Upvotes: 0

Jordi Gomis
Jordi Gomis

Reputation: 63

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,}

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163577

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}`)
);

Upvotes: 8

Mosia Thabo
Mosia Thabo

Reputation: 4267

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

Upvotes: 5

Steve Johnson
Steve Johnson

Reputation: 3114

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.

Upvotes: 11

nakorndev
nakorndev

Reputation: 919

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

Upvotes: 2

Sazzad
Sazzad

Reputation: 306

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.

Upvotes: 15

Wprog_dy
Wprog_dy

Reputation: 65

     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.');

Upvotes: -2

Masoud
Masoud

Reputation: 342

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

Upvotes: 3

Hasan Tezcan
Hasan Tezcan

Reputation: 1232

/^(?=.*[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'
    ),

Upvotes: 5

Milan Paudyal
Milan Paudyal

Reputation: 561

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+,.\\\/;':"-]).{8,}$
    

Upvotes: 10

Venkatesh
Venkatesh

Reputation: 299

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}$

Upvotes: 0

Anup Seth
Anup Seth

Reputation: 31

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.

Upvotes: 1

Dana
Dana

Reputation: 161

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.

Upvotes: 12

MiKr13
MiKr13

Reputation: 1511

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}`);
    });
}

Upvotes: 4

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/

Upvotes: 11

Anand Raja
Anand Raja

Reputation: 3126

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

Upvotes: 1

Carette
Carette

Reputation: 11

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,}"

Upvotes: -1

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20196

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

Upvotes: 3

Frithjof Schaefer
Frithjof Schaefer

Reputation: 1205

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

Upvotes: 2

anubhava
anubhava

Reputation: 785856

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)

Upvotes: 806

Stefano
Stefano

Reputation: 1856

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.

Upvotes: 4

Tai Ho
Tai Ho

Reputation: 576

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

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

Upvotes: 1

Srinivas
Srinivas

Reputation: 23999

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}$"

Upvotes: 2361

Related Questions