[javascript] 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:

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?

This question is related to javascript asp.net regex

The answer is


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

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&*\-_+=[\]{}|\\:',?/`~"();!])([A-Za-z\d@#$%^&*\-_+=[\]{}|\\:',?/`~"();!]|\.(?!@)){6,16}$

Testing this one in 2020:

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

Verify yourself

_x000D_
_x000D_
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;_x000D_
const str = `some12*Nuts`;_x000D_
let m;_x000D_
_x000D_
if ((m = regex.exec(str)) !== null) {_x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_


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.

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

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

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

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/


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

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

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


Demo:

_x000D_
_x000D_
function password_check() {_x000D_
  pass = document.getElementById("password").value;_x000D_
  console.log(pass);_x000D_
  regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;_x000D_
  if (regex.exec(pass) == null) {_x000D_
    alert('invalid password!')_x000D_
  }_x000D_
  else {_x000D_
    console.log("valid");_x000D_
  }_x000D_
}
_x000D_
<input type="text" id="password" value="Sample@1">_x000D_
<input type="button" id="submit" onclick="password_check()" value="submit">
_x000D_
_x000D_
_x000D_


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.

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

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

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

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


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

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


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

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


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

I would reply to Peter Mortensen, but I don't have enough reputation.

His expressions are perfect for each of the specified minimum requirements. The problem with his expressions that don't require special characters is that they also don't ALLOW special characters, so they also enforce maximum requirements, which I don't believe the OP requested. Normally you want to allow your users to make their password as strong as they want; why restrict strong passwords?

So, his "minimum eight characters, at least one letter and one number" expression:

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

achieves the minimum requirement, but the remaining characters can only be letter and numbers. To allow (but not require) special characters, you should use something like:

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

or

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

Likewise, "minimum eight characters, at least one uppercase letter, one lowercase letter and one number:"

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

meets that minimum requirement, but only allows letters and numbers. Use:

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

or

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


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


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

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


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
}

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

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.


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

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

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


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.


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

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

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.


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)

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?