Trying to create a robust password rule for JavaScript using regex led to some unexpected results.
Initially, the following approach worked well:
const value = 'TTest90()';
const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-_+?.]){2,}).{8,}$/.test(value);
The variable firstApproach
returned true as expected.
Next, attempting a different approach using new RegExp resulted in:
const pattern = '/^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-_+?.]){2,}).{8,}$/';
const regex = new RegExp(pattern);
const secondApproach = regex.test(value);
Surprisingly, secondApproach
now evaluates to false even with the same regex pattern.
The reason behind why secondApprocach
is not returning true remains unclear, and I am determined to uncover where the error lies. Thank you!