Regular Expression for password validation - javascript

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
}

Related

Password policy requirement regex

I need a regex to meet this password policy requirement
Minimum eight (8) characters
At least one number (0-9)
Any three of the following:
Lowercase
Uppercase
Number
Special character ( ! " # $ % & ' ( )
* + , - . / : ; < = > ? # [ \ ] ^ _ ` { | } ~ )
for now i am using this regex Minimum eight (8) characters
/^(?=.*\d)[ !#$%&()*+,.\/:;<=>?#[\]^`{|}~\w-]{8,}$/
This regex is not working as expected it is taking input of
testtest1 as a right match.It should take this test#test1,Testtest12 as a right input
The pattern will match testtest1 as you are only asserting a required digit and following character class [ !#$%&()*+,.\/:;<=>?#[\]^{|}~\w-]{8,}` will repeat matching at least 8 times any of the listed.
If you want to assert either an uppercase char A-Z or a special character as well, you could use another positive lookahead with an alternation
^(?=.*\d)(?=.*(?:[A-Z]|[!#$%&()*+,.\/:;<=>?#[\]^`{|}~-]))[!#$%&()*+,.\/:;<=>?#[\]^`{|}~\w-]{8,}$
Regex demo
Note that I omitted matching the spaces, you could a space to the character class if you want to match it (Not sure if you would allow spaces in the password)
You need to change your lookahead part a bit.
^(?=.{8,})(?=.*[0-9].*)(.*[\!"#$%&'\(\)\*+,\-.\/:;<=>?#\[\\\]^_`{|}~].*){3,}
(?=.{8,}) = minimum eight characters length (positive lookahead)
(?=.*[0-9].*) = at leats one number (positive lookahead)
(.*[\!"#$%&'\(\)\*+,\-.\/:;<=>?#\[\\\]^_{|}~].*){3,}` any character in your list somewhere at least three times

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
}

Regular expression to validate current DoD Password Standards

Here are two different ones that are not working yet.
One:
^[a-zA-Z0-9\{\}:;,.?\-=+|<>!##$%^&()\[\]\/\\)]{15,}
Two:
(?=^.{15,}$)(?=.*\d{2,})(?=.*\W+)(?![.\n])(?=.*[A-Z]{2,})(?=.*[a-z]{2,}).*$
Rules:
Passwords must be at least 15 characters in length.
Passwords must contain at least 2 character(s) from each of these 4 categories:
uppercase alphabetical A-Z
lowercase alphabetical a-z
numeric 0-9
special characters {}:;,.?-=+|<>!##$%^&()[]/\
Passwords must not contain any spaces.
Thanks for any help.
---- Edited ----
Some Samples to try
2wsx#WSX3edc#EDC
3edc#EDC4rfv$RFV
nhy6NHY^mju7MJU&
1qaz!QAZ2wsx#WSX
I have tested them at http://www.gskinner.com/RegExr/ and I am not getting them to work.
I feel like some of the below examples should work but they don't or I must be doing something wrong.
Either check these regexes in one after another or create one big look-ahead-based expression from them.
Rules:
Passwords must be at least 15 characters in length.
^.{15,}$
Passwords must contain at least 2 character(s) from each of these 4 categories:
uppercase alphabetical (A-Z)
^(.*?[A-Z]){2}
lowercase alphabetical (a-z)
^(.*?[a-z]){2}
numeric (0-9)
^(.*?[0-9]){2}
special characters ({}:;,.?-=+|<>!##$%^&()[]/)
^(.*?[{}:;,.?\-=+|!##$%^&()\[\]/]){2}
Passwords must not contain any spaces.
Why? But if you must, change the first expression to
^\S{15,}$
Why do it all in one regex? Do something like:
if( length($password) >= 15 &&
($password =~ y/A-Z//) >= 2 &&
($password =~ y/a-z//) >= 2 &&
($password =~ y/0-9//) >= 2 &&
($password =~ y/{}:;,.?\-=+|<>!##%^&()\[\]///) >= 2 &&
$password =~ /^\S+$/ ) {
print "password validates!\n";
} else {
print "password doesn't validate!\n";
}
This way when you have to add more criteria, it's easy to do. This is also a hell of a lot more readable and maintainable than putting it all in one giant regex.
I found the answer.... for JavaScript... Thanks for all the help.
This one works.
^((?=(.*[\d]){2,})(?=(.*[a-z]){2,})(?=(.*[A-Z]){2,})(?=(.*[^\w\d\s]){2,})).{15,}$
^(?!.* )(?=.{15})(?=.*[A-Z].*[A-Z])(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9])(?=.*[{}:;,.?\-=+|<>!##$%\^&()[\]/\\].*[{}:;,.?\-=+|<>!##$%\^&()[\]/\\])
My Regex should work even for separated chars. So for example Ab0%Ab0%0000000000000 (you see, there isn't an AA, the two A are separated). I have escape the minimum number of characters (only ^ and ])
^ Beginning of the string
(?!.* ) Not (any character repeated * times followed by a space)
(?=.{15}) Any character for 15 times (as it's written, even if there are other characters after the 15th it won't change anything)
(?=.*[A-Z].*[A-Z]) Any character repeated * times, an Upper Case letter, any character repeated * times, an Upper Case letter
(?=.*[a-z].*[a-z]) Any character repeated * times, a Lower Case letter, any character repeated * times, a Lower Case letter
(?=.*[0-9].*[0-9]) Any character repeated * times, a Digit, any character repeated * times, a Digit
(?=.*[{}:;,.?\-=+|<>!##$%\^&()[\]/\\].*[{}:;,.?\-=+|<>!##$%\^&()[\]/\\]) Any character repeated * times, a Symbol, any character repeated * times, a Symbol
All the subexpression are zero-width look-ahead (or zero-width negative look-ahead) and they start all at the first character, so they are all in "and" and they must be all true.

Categories

Resources