regex match password requirements [duplicate] - javascript

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?

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

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)

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.

Use the following Regex to satisfy the below conditions:
Conditions:
Min 1 uppercase letter.
Min 1 lowercase letter.
Min 1 special character.
Min 1 number.
Min 8 characters.
Max 30 characters.
Regex:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$#!%&*?])[A-Za-z\d#$#!%&*?]{8,30}$/

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

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

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

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.

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

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)
});
At least one upper case English letter
At least one lower case English letter
At least one digit
At least one special character

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.

Try this one:
Minimum six characters
At least one uppercase character
At least one lowercase character
At least one special character
Expression:
"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&.])[A-Za-z\d$#$!%*?&.]{6, 20}/"
Optional Special Characters:
At least one special character
At least one number
Special characters are optional
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

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.

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
}

For a more strict validation where the following is required:
At least One Upper Case Character
At least one Lower Case character
At least one digit
At least one symbol/special character #$!%*#?&^_-
Minimum 8 characters/digits
Regex:
/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#$!%*#?&^_-]).{8,}/
I hope it helps someone with a more stringent.

What about considering the following regex solution:
^(?=.*[\w])(?=.*[\W])[\w\W]{8,}$
Which validates the following:
At least one lowercase
At least one uppercase
At least one digit
At least one special character
At least it should have 8 characters long.
Check it out working at the following link https://regex101.com/r/qPmC06/4/

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

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

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

#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 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:
doesn't use \w because that includes _, which I'm testing for.
I've had lots of troubles matching symbols, without matching the end of the line.
Doesn't specify symbols specifically, this is also because different locales may have different symbols on their keyboards that they may want to use.

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

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

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
.{0,7} - matches if password has between 0 to 7 characters.
[^a-z]{1,} - matches if no lower case is found
[^A-Z]{1,} - matches if no upper case is found
[^\d]{1,} - matches if no number (between [0-9]) is found
[\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].

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

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

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

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.

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

Related

How to use RegExp to check if string have at least two upper case letters but not one after another [duplicate]

My password strength criteria is as below :
8 characters length
2 letters in Upper Case
1 Special Character (!##$&*)
2 numerals (0-9)
3 letters in Lower Case
Can somebody please give me regex for same. All conditions must be met by password .
You can do these checks using positive look ahead assertions:
^(?=.*[A-Z].*[A-Z])(?=.*[!##$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$
Rubular link
Explanation:
^ Start anchor
(?=.*[A-Z].*[A-Z]) Ensure string has two uppercase letters.
(?=.*[!##$&*]) Ensure string has one special case letter.
(?=.*[0-9].*[0-9]) Ensure string has two digits.
(?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
.{8} Ensure string is of length 8.
$ End anchor.
You should also consider changing some of your rules to:
Add more special characters i.e. %, ^, (, ), -, _, +, and period. I'm adding all the special characters that you missed above the number signs in US keyboards. Escape the ones regex uses.
Make the password 8 or more characters. Not just a static number 8.
With the above improvements, and for more flexibility and readability, I would modify the regex to.
^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!##$%^&*()\-__+.]){1,}).{8,}$
Basic Explanation
(?=(.*RULE){MIN_OCCURANCES,})
Each rule block is shown by (?=(){}). The rule and number of occurrences can then be easily specified and tested separately, before getting combined
Detailed Explanation
^ start anchor
(?=(.*[a-z]){3,}) lowercase letters. {3,} indicates that you want 3 of this group
(?=(.*[A-Z]){2,}) uppercase letters. {2,} indicates that you want 2 of this group
(?=(.*[0-9]){2,}) numbers. {2,} indicates that you want 2 of this group
(?=(.*[!##$%^&*()\-__+.]){1,}) all the special characters in the [] fields. The ones used by regex are escaped by using the \ or the character itself. {1,} is redundant, but good practice, in case you change that to more than 1 in the future. Also keeps all the groups consistent
{8,} indicates that you want 8 or more
$ end anchor
And lastly, for testing purposes here is a robulink with the above regex
Answers given above are perfect but I suggest to use multiple smaller regex rather than a big one.
Splitting the long regex have some advantages:
easiness to write and read
easiness to debug
easiness to add/remove part of regex
Generally this approach keep code easily maintainable.
Having said that, I share a piece of code that I write in Swift as example:
struct RegExp {
/**
Check password complexity
- parameter password: password to test
- parameter length: password min length
- parameter patternsToEscape: patterns that password must not contains
- parameter caseSensitivty: specify if password must conforms case sensitivity or not
- parameter numericDigits: specify if password must conforms contains numeric digits or not
- returns: boolean that describes if password is valid or not
*/
static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool {
if (password.length < length) {
return false
}
if caseSensitivty {
let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0
if !hasUpperCase {
return false
}
let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0
if !hasLowerCase {
return false
}
}
if numericDigits {
let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0
if !hasNumbers {
return false
}
}
if patternsToEscape.count > 0 {
let passwordLowerCase = password.lowercaseString
for pattern in patternsToEscape {
let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0
if hasMatchesWithPattern {
return false
}
}
}
return true
}
static func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
You can use zero-length positive look-aheads to specify each of your constraints separately:
(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!##$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})
If your regex engine doesn't support the \p notation and pure ASCII is enough, then you can replace \p{Lu} with [A-Z] and \p{Ll} with [a-z].
All of above regex unfortunately didn't worked for me.
A strong password's basic rules are
Should contain at least a capital letter
Should contain at least a small letter
Should contain at least a number
Should contain at least a special character
And minimum length
So, Best Regex would be
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*]).{8,}$
The above regex have minimum length of 8. You can change it from {8,} to {any_number,}
Modification in rules?
let' say you want minimum x characters small letters, y characters capital letters, z characters numbers, Total minimum length w. Then try below regex
^(?=.*[a-z]{x,})(?=.*[A-Z]{y,})(?=.*[0-9]{z,})(?=.*[!##\$%\^&\*]).{w,}$
Note: Change x, y, z, w in regex
Edit: Updated regex answer
Edit2: Added modification
I would suggest adding
(?!.*pass|.*word|.*1234|.*qwer|.*asdf) exclude common passwords
import re
RegexLength=re.compile(r'^\S{8,}$')
RegexDigit=re.compile(r'\d')
RegexLower=re.compile(r'[a-z]')
RegexUpper=re.compile(r'[A-Z]')
def IsStrongPW(password):
if RegexLength.search(password) == None or RegexDigit.search(password) == None or RegexUpper.search(password) == None or RegexLower.search(password) == None:
return False
else:
return True
while True:
userpw=input("please input your passord to check: \n")
if userpw == "exit":
break
else:
print(IsStrongPW(userpw))
codaddict's solution works fine, but this one is a bit more efficient: (Python syntax)
password = re.compile(r"""(?#!py password Rev:20160831_2100)
# Validate password: 2 upper, 1 special, 2 digit, 1 lower, 8 chars.
^ # Anchor to start of string.
(?=(?:[^A-Z]*[A-Z]){2}) # At least two uppercase.
(?=[^!##$&*]*[!##$&*]) # At least one "special".
(?=(?:[^0-9]*[0-9]){2}) # At least two digit.
.{8,} # Password length is 8 or more.
$ # Anchor to end of string.
""", re.VERBOSE)
The negated character classes consume everything up to the desired character in a single step, requiring zero backtracking. (The dot star solution works just fine, but does require some backtracking.) Of course with short target strings such as passwords, this efficiency improvement will be negligible.
For PHP, this works fine!
if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/",
'CaSu4Li8')){
return true;
}else{
return fasle;
}
in this case the result is true
Thsks for #ridgerunner
Another solution:
import re
passwordRegex = re.compile(r'''(
^(?=.*[A-Z].*[A-Z]) # at least two capital letters
(?=.*[!##$&*]) # at least one of these special c-er
(?=.*[0-9].*[0-9]) # at least two numeric digits
(?=.*[a-z].*[a-z].*[a-z]) # at least three lower case letters
.{8,} # at least 8 total digits
$
)''', re.VERBOSE)
def userInputPasswordCheck():
print('Enter a potential password:')
while True:
m = input()
mo = passwordRegex.search(m)
if (not mo):
print('''
Your password should have at least one special charachter,
two digits, two uppercase and three lowercase charachter. Length: 8+ ch-ers.
Enter another password:''')
else:
print('Password is strong')
return
userInputPasswordCheck()
Password must meet at least 3 out of the following 4 complexity rules,
[at least 1 uppercase character (A-Z)
at least 1 lowercase character (a-z)
at least 1 digit (0-9)
at least 1 special character — do not forget to treat space as special characters too]
at least 10 characters
at most 128 characters
not more than 2 identical characters in a row (e.g., 111 not allowed)
'^(?!.(.)\1{2})
((?=.[a-z])(?=.[A-Z])(?=.[0-9])|(?=.[a-z])(?=.[A-Z])(?=.[^a-zA-Z0-9])|(?=.[A-Z])(?=.[0-9])(?=.[^a-zA-Z0-9])|(?=.[a-z])(?=.[0-9])(?=.*[^a-zA-Z0-9])).{10,127}$'
(?!.*(.)\1{2})
(?=.[a-z])(?=.[A-Z])(?=.*[0-9])
(?=.[a-z])(?=.[A-Z])(?=.*[^a-zA-Z0-9])
(?=.[A-Z])(?=.[0-9])(?=.*[^a-zA-Z0-9])
(?=.[a-z])(?=.[0-9])(?=.*[^a-zA-Z0-9])
.{10.127}

Password validation - lowercase, uppercase, numbers and special characters [duplicate]

My password strength criteria is as below :
8 characters length
2 letters in Upper Case
1 Special Character (!##$&*)
2 numerals (0-9)
3 letters in Lower Case
Can somebody please give me regex for same. All conditions must be met by password .
You can do these checks using positive look ahead assertions:
^(?=.*[A-Z].*[A-Z])(?=.*[!##$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$
Rubular link
Explanation:
^ Start anchor
(?=.*[A-Z].*[A-Z]) Ensure string has two uppercase letters.
(?=.*[!##$&*]) Ensure string has one special case letter.
(?=.*[0-9].*[0-9]) Ensure string has two digits.
(?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
.{8} Ensure string is of length 8.
$ End anchor.
You should also consider changing some of your rules to:
Add more special characters i.e. %, ^, (, ), -, _, +, and period. I'm adding all the special characters that you missed above the number signs in US keyboards. Escape the ones regex uses.
Make the password 8 or more characters. Not just a static number 8.
With the above improvements, and for more flexibility and readability, I would modify the regex to.
^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!##$%^&*()\-__+.]){1,}).{8,}$
Basic Explanation
(?=(.*RULE){MIN_OCCURANCES,})
Each rule block is shown by (?=(){}). The rule and number of occurrences can then be easily specified and tested separately, before getting combined
Detailed Explanation
^ start anchor
(?=(.*[a-z]){3,}) lowercase letters. {3,} indicates that you want 3 of this group
(?=(.*[A-Z]){2,}) uppercase letters. {2,} indicates that you want 2 of this group
(?=(.*[0-9]){2,}) numbers. {2,} indicates that you want 2 of this group
(?=(.*[!##$%^&*()\-__+.]){1,}) all the special characters in the [] fields. The ones used by regex are escaped by using the \ or the character itself. {1,} is redundant, but good practice, in case you change that to more than 1 in the future. Also keeps all the groups consistent
{8,} indicates that you want 8 or more
$ end anchor
And lastly, for testing purposes here is a robulink with the above regex
Answers given above are perfect but I suggest to use multiple smaller regex rather than a big one.
Splitting the long regex have some advantages:
easiness to write and read
easiness to debug
easiness to add/remove part of regex
Generally this approach keep code easily maintainable.
Having said that, I share a piece of code that I write in Swift as example:
struct RegExp {
/**
Check password complexity
- parameter password: password to test
- parameter length: password min length
- parameter patternsToEscape: patterns that password must not contains
- parameter caseSensitivty: specify if password must conforms case sensitivity or not
- parameter numericDigits: specify if password must conforms contains numeric digits or not
- returns: boolean that describes if password is valid or not
*/
static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool {
if (password.length < length) {
return false
}
if caseSensitivty {
let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0
if !hasUpperCase {
return false
}
let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0
if !hasLowerCase {
return false
}
}
if numericDigits {
let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0
if !hasNumbers {
return false
}
}
if patternsToEscape.count > 0 {
let passwordLowerCase = password.lowercaseString
for pattern in patternsToEscape {
let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0
if hasMatchesWithPattern {
return false
}
}
}
return true
}
static func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
You can use zero-length positive look-aheads to specify each of your constraints separately:
(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!##$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})
If your regex engine doesn't support the \p notation and pure ASCII is enough, then you can replace \p{Lu} with [A-Z] and \p{Ll} with [a-z].
All of above regex unfortunately didn't worked for me.
A strong password's basic rules are
Should contain at least a capital letter
Should contain at least a small letter
Should contain at least a number
Should contain at least a special character
And minimum length
So, Best Regex would be
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*]).{8,}$
The above regex have minimum length of 8. You can change it from {8,} to {any_number,}
Modification in rules?
let' say you want minimum x characters small letters, y characters capital letters, z characters numbers, Total minimum length w. Then try below regex
^(?=.*[a-z]{x,})(?=.*[A-Z]{y,})(?=.*[0-9]{z,})(?=.*[!##\$%\^&\*]).{w,}$
Note: Change x, y, z, w in regex
Edit: Updated regex answer
Edit2: Added modification
I would suggest adding
(?!.*pass|.*word|.*1234|.*qwer|.*asdf) exclude common passwords
import re
RegexLength=re.compile(r'^\S{8,}$')
RegexDigit=re.compile(r'\d')
RegexLower=re.compile(r'[a-z]')
RegexUpper=re.compile(r'[A-Z]')
def IsStrongPW(password):
if RegexLength.search(password) == None or RegexDigit.search(password) == None or RegexUpper.search(password) == None or RegexLower.search(password) == None:
return False
else:
return True
while True:
userpw=input("please input your passord to check: \n")
if userpw == "exit":
break
else:
print(IsStrongPW(userpw))
codaddict's solution works fine, but this one is a bit more efficient: (Python syntax)
password = re.compile(r"""(?#!py password Rev:20160831_2100)
# Validate password: 2 upper, 1 special, 2 digit, 1 lower, 8 chars.
^ # Anchor to start of string.
(?=(?:[^A-Z]*[A-Z]){2}) # At least two uppercase.
(?=[^!##$&*]*[!##$&*]) # At least one "special".
(?=(?:[^0-9]*[0-9]){2}) # At least two digit.
.{8,} # Password length is 8 or more.
$ # Anchor to end of string.
""", re.VERBOSE)
The negated character classes consume everything up to the desired character in a single step, requiring zero backtracking. (The dot star solution works just fine, but does require some backtracking.) Of course with short target strings such as passwords, this efficiency improvement will be negligible.
For PHP, this works fine!
if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/",
'CaSu4Li8')){
return true;
}else{
return fasle;
}
in this case the result is true
Thsks for #ridgerunner
Another solution:
import re
passwordRegex = re.compile(r'''(
^(?=.*[A-Z].*[A-Z]) # at least two capital letters
(?=.*[!##$&*]) # at least one of these special c-er
(?=.*[0-9].*[0-9]) # at least two numeric digits
(?=.*[a-z].*[a-z].*[a-z]) # at least three lower case letters
.{8,} # at least 8 total digits
$
)''', re.VERBOSE)
def userInputPasswordCheck():
print('Enter a potential password:')
while True:
m = input()
mo = passwordRegex.search(m)
if (not mo):
print('''
Your password should have at least one special charachter,
two digits, two uppercase and three lowercase charachter. Length: 8+ ch-ers.
Enter another password:''')
else:
print('Password is strong')
return
userInputPasswordCheck()
Password must meet at least 3 out of the following 4 complexity rules,
[at least 1 uppercase character (A-Z)
at least 1 lowercase character (a-z)
at least 1 digit (0-9)
at least 1 special character — do not forget to treat space as special characters too]
at least 10 characters
at most 128 characters
not more than 2 identical characters in a row (e.g., 111 not allowed)
'^(?!.(.)\1{2})
((?=.[a-z])(?=.[A-Z])(?=.[0-9])|(?=.[a-z])(?=.[A-Z])(?=.[^a-zA-Z0-9])|(?=.[A-Z])(?=.[0-9])(?=.[^a-zA-Z0-9])|(?=.[a-z])(?=.[0-9])(?=.*[^a-zA-Z0-9])).{10,127}$'
(?!.*(.)\1{2})
(?=.[a-z])(?=.[A-Z])(?=.*[0-9])
(?=.[a-z])(?=.[A-Z])(?=.*[^a-zA-Z0-9])
(?=.[A-Z])(?=.[0-9])(?=.*[^a-zA-Z0-9])
(?=.[a-z])(?=.[0-9])(?=.*[^a-zA-Z0-9])
.{10.127}

Need to build regex to validate password field [duplicate]

can any one help me in creating a regular expression for password validation.
The Condition is "Password must contain 8 characters and at least one number, one letter and one unique character such as !#$%&? "
^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$
---
^.* : Start
(?=.{8,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
.*$ : End
Try this
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{6,20})
Description of above Regular Expression:
( # Start of group
(?=.*\d) # must contains one digit from 0-9
(?=.*[a-z]) # must contains one lowercase characters
(?=.*[\W]) # must contains at least one special character
. # match anything with previous condition checking
{8,20} # length at least 8 characters and maximum of 20
) # End of group
"/W" will increase the range of characters that can be used for password and pit can be more safe.
You can achieve each of the individual requirements easily enough (e.g. minimum 8 characters: .{8,} will match 8 or more characters).
To combine them you can use "positive lookahead" to apply multiple sub-expressions to the same content. Something like (?=.*\d.*).{8,} to match one (or more) digits with lookahead, and 8 or more characters.
So:
(?=.*\d.*)(?=.*[a-zA-Z].*)(?=.*[!#\$%&\?].*).{8,}
Remembering to escape meta-characters.
Password with the following conditions:
At least 1 digit
At least 2 special characters
At least 1 alphabetic character
No blank space
'use strict';
(function() {
var foo = '3g^g$';
console.log(/^(?=.*\d)(?=(.*\W){2})(?=.*[a-zA-Z])(?!.*\s).{1,15}$/.test(foo));
/**
* (?=.*\d) should contain at least 1 digit
* (?=(.*\W){2}) should contain at least 2 special characters
* (?=.*[a-zA-Z]) should contain at least 1 alphabetic character
* (?!.*\s) should not contain any blank space
*/
})();
You can make your own regular expression for javascript validations;
(/^
(?=.*\d) //should contain at least one digit
(?=.*[a-z]) //should contain at least one lower case
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{8,} //should contain at least 8 from the mentioned characters
$/)
Example:- /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/
var regularExpression = new RegExp("^^(?=.*[A-Z]{"+minUpperCase+",})" +
"(?=.*[a-z]{"+minLowerCase+",})(?=.*[0-9]{"+minNumerics+",})" +
"(?=.*[!##$\-_?.:{]{"+minSpecialChars+",})" +
"[a-zA-Z0-9!##$\-_?.:{]{"+minLength+","+maxLength+"}$");
if (pswd.match(regularExpression)) {
//Success
}

Js regex validation for password [duplicate]

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?
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}$"
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)
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.
Use the following Regex to satisfy the below conditions:
Conditions:
Min 1 uppercase letter.
Min 1 lowercase letter.
Min 1 special character.
Min 1 number.
Min 8 characters.
Max 30 characters.
Regex:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$#!%&*?])[A-Za-z\d#$#!%&*?]{8,30}$/
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
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
 
✅ 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.
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.
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/>');
});
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)
});
At least one upper case English letter
At least one lower case English letter
At least one digit
At least one special character
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.
Try this one:
Minimum six characters
At least one uppercase character
At least one lowercase character
At least one special character
Expression:
"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&.])[A-Za-z\d$#$!%*?&.]{6, 20}/"
Optional Special Characters:
At least one special character
At least one number
Special characters are optional
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
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.
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
}
For a more strict validation where the following is required:
At least One Upper Case Character
At least one Lower Case character
At least one digit
At least one symbol/special character #$!%*#?&^_-
Minimum 8 characters/digits
Regex:
/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#$!%*#?&^_-]).{8,}/
I hope it helps someone with a more stringent.
What about considering the following regex solution:
^(?=.*[\w])(?=.*[\W])[\w\W]{8,}$
Which validates the following:
At least one lowercase
At least one uppercase
At least one digit
At least one special character
At least it should have 8 characters long.
Check it out working at the following link https://regex101.com/r/qPmC06/4/
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*()_+,.\\\/;':"-]).{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}`)
);
/^(?=.*[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'
),
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}`);
});
}
#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 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:
doesn't use \w because that includes _, which I'm testing for.
I've had lots of troubles matching symbols, without matching the end of the line.
Doesn't specify symbols specifically, this is also because different locales may have different symbols on their keyboards that they may want to use.
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">
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
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
.{0,7} - matches if password has between 0 to 7 characters.
[^a-z]{1,} - matches if no lower case is found
[^A-Z]{1,} - matches if no upper case is found
[^\d]{1,} - matches if no number (between [0-9]) is found
[\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].
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+-]).{6}
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);
}
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
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.
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})

How to validate a password allows at least 4 digits and 1 character without special character using regular expression?

How to validate a password allows at least 4 digits and 1 character without special character using regular expression?
Password Valid Format: 1234a or 6778B or 67A89 (Without Special Characters Like #$%^&*/)
Maximum Password Length : 5 Characters Long
Can any one help me how to do this?.
Thanks.
The pattern you want
any number of numbers
then a letter
any number of numbers
additional restriction as in all should not be longer than 5 chars
The patter could be this: (using positive lookahead to check the numbers-letter-numbers combination then checking for 5 characters to check length)
/^(?=[0-9]*[a-zA-Z][0-9]*$).{5}$/
This regex should work:
^(?=(.*?[0-9]){4})(?=.*?[a-zA-Z])[0-9A-Za-z]{5}$
Since we are only allowing [0-9A-Za-z]{5} symbols in password there is no need to check for special characters here.
Online Demo: http://regex101.com/r/mB6sS5
Explanation:
(?=(.*?[0-9]){4}) - Lookahead to check for presence of at least 4 numbers
(?=.*?[a-zA-Z]) - Lookahead to check for presence at least 1 letter
[0-9A-Za-z]{5} Only allows symbols in character class with max length=5
^[0-9]{4}[A-Za-z]{1}$
This will let you enter four numbers (0-9) and 1 letter (a-z and A-Z) example 1234a.... hope this is the answer you were looking for.
Below is the javascript code for doing the checking you need
var regex =^(?=(.*?[0-9]){4})(?=.*?[a-zA-Z])[0-9A-Za-z]{5}$;
var input = "1234B";
if(regex.test(input)) {
alert(matches[match]);
} else
{
alert("No matches found!");
}

Categories

Resources