Regex Password Validation
Description
You need to write regex that will validate a password to make sure it meets the following criteria:
At least six characters long
contains a lowercase letter
contains an uppercase letter
contains a number
Valid passwords will only be alphanumeric characters.
My answer
function validate(password) {
return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/.test(password);
}
Other solutions
function validate(password) {
return /^[A-Za-z0-9]{6,}$/.test(password) &&
/[A-Z]+/ .test(password) &&
/[a-z]+/ .test(password) &&
/[0-9]+/ .test(password) ;
}
Wrap up
Regular expression - Assertions
Type
Boundary-type assertions
- ^
Matches the beginning of input. /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".
- Matchestheendofinput.Forexample,/t/ does not match the "t" in "eater", but does match it in "eat".
- \b
Matches a word boundary. Examples:
/\bm/ matches the "m" in "moon".
/oo\b/ does not match the "oo" in "moon", because "oo" is followed by "n" which is a word character.
/oon\b/ matches the "oon" in "moon", because "oon" is the end of the string, thus not followed by a word character.
/\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.
- \B
Matches a non-word boundary. For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".
Other assertions
- x(?=y): Lookahead assertion
Matches "x" only if "x" is followed by "y". For example, /Jack(?=Sprat)/ matches "Jack" only if it is followed by "Sprat".
/Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.
- x(?!y): Negative lookahead assertion
Matches "x" only if "x" is not followed by "y". For example, /\d+(?!.)/ matches a number only if it is not followed by a decimal point. /\d+(?!.)/.exec('3.141') matches "141" but not "3.
- (?<=y)x: Lookbehind assertion
Matches "x" only if "x" is preceded by "y". For example, /(?<=Jack)Sprat/ matches "Sprat" only if it is preceded by "Jack". /(?<=Jack|Tom)Sprat/ matches "Sprat" only if it is preceded by "Jack" or "Tom". However, neither "Jack" nor "Tom" is part of the match results.
- (?<!y)x: Negative lookbehind assertion
Matches "x" only if "x" is not preceded by "y". For example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign.
source: mdn web docs