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:
JavaScript
x
2
1
^(?=.{10,16}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?W).*$
2
Advertisement
Answer
Interesting problem! You can use an OR pattern: ^((...)|(...))
where you test separately for two or three combinations. Test case:
JavaScript
1
15
15
1
[
2
'1234567890123456', // fail, only numbers
3
'abcdefghijklmnop', // fail, only letters
4
'12345a678', // fail, 2 combinations, too short
5
'12345a678b', // pass, 2 combinations, 10 chars
6
'12345a67890bcdef', // pass, 2 combinations, 16 chars
7
'12345a67890bcdefg',// fail, 2 combinations, too long
8
'12+34ab', // fail, 3 combinations, too short
9
'12+34abc', // pass, 3 combinations, 8 chars
10
'12+34567890ab$cd', // pass, 3 combinations, 19 chars
11
'12+34567890ab$cde' // fail, 3 combinations, too long
12
].forEach(str => {
13
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])))/;
14
console.log(str + (re.test(str) ? ' => pass' : ' => fail'));
15
});
Result:
JavaScript
1
11
11
1
1234567890123456 => fail
2
abcdefghijklmnop => fail
3
12345a678 => fail
4
12345a678b => pass
5
12345a67890bcdef => pass
6
12345a67890bcdefg => fail
7
12+34ab => fail
8
12+34abc => pass
9
12+34567890ab$cd => pass
10
12+34567890ab$cde => fail
11
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