so im having trouble writing regex in javascript. I want to practice using conditionals on regex.
Problem i want to solve:
- combinations of (small/capital letters) + (numbers) + (special characters)
- if using two of the possible combinations, the length should be from 10-16 long
- if using three of the possible combinations, the length should be from 8-16 long
Regex for combinations:
^(?=.{10,16}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?W).*$
Advertisement
Answer
Interesting problem! You can use an OR pattern: ^((...)|(...)) where you test separately for two or three combinations. Test case:
[
'1234567890123456', // fail, only numbers
'abcdefghijklmnop', // fail, only letters
'12345a678', // fail, 2 combinations, too short
'12345a678b', // pass, 2 combinations, 10 chars
'12345a67890bcdef', // pass, 2 combinations, 16 chars
'12345a67890bcdefg',// fail, 2 combinations, too long
'12+34ab', // fail, 3 combinations, too short
'12+34abc', // pass, 3 combinations, 8 chars
'12+34567890ab$cd', // pass, 3 combinations, 19 chars
'12+34567890ab$cde' // fail, 3 combinations, too long
].forEach(str => {
const re = /^(((?=.{10,16}$)(?=.*?[a-zA-Z])(?=.*?[0-9]))|((?=.{10,16}$)(?=.*?[a-zA-Z])(?=.*?[W]))|((?=.{10,16}$)(?=.*?[0-9])(?=.*?[W]))|((?=.{8,16}$)(?=.*?[a-zA-Z])(?=.*?[0-9])(?=.*?[W])))/;
console.log(str + (re.test(str) ? ' => pass' : ' => fail'));
});Result:
1234567890123456 => fail abcdefghijklmnop => fail 12345a678 => fail 12345a678b => pass 12345a67890bcdef => pass 12345a67890bcdefg => fail 12+34ab => fail 12+34abc => pass 12+34567890ab$cd => pass 12+34567890ab$cde => fail
Explanation of regex:
^— anchor at start of string((..A..)|(..B..)|(..C..)|(..D..))— logical OR of parts …A… to …D…- part …A…:
(?=.{10,16}$)— positive lookahead for 10 to 16 chars, AND(?=.*?[a-zA-Z])— positive lookahead for an upper or lowercase letter, AND(?=.*?[0-9])— positive lookahead for a number
- part …B…:
(?=.{10,16}$)— positive lookahead for 10 to 16 chars, AND(?=.*?[a-zA-Z])— positive lookahead for an upper or lowercase letter, AND(?=.*?[W])— positive lookahead for a special char
- part …C…:
(?=.{10,16}$)— positive lookahead for 10 to 16 chars, AND(?=.*?[0-9])— positive lookahead for a number, AND(?=.*?[W])— positive lookahead for a special char
- part …D…:
(?=.{8,16}$)— positive lookahead for 8 to 16 chars, AND(?=.*?[a-zA-Z])— positive lookahead for an upper or lowercase letter, AND(?=.*?[0-9])— positive lookahead for a number(?=.*?[W])— positive lookahead for a special char