DEV Community

Cover image for Regex for Passwords
Temitope Ayodele
Temitope Ayodele

Posted on

Regex for Passwords

Minimum eight characters, at least one letter and one number:

"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
Enter fullscreen mode Exit fullscreen mode

Minimum eight characters, at least one letter, one number and one special character:

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$"
Enter fullscreen mode Exit fullscreen mode

Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
Enter fullscreen mode Exit fullscreen mode

Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
Enter fullscreen mode Exit fullscreen mode

Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,10}$"
Enter fullscreen mode Exit fullscreen mode

Latest comments (1)

Collapse
 
moopet profile image
Ben Sinclair

I think this isn't a good approach.

People often complain that regular expressions are difficult to read, whereas I often come down on the other side, saying that they can be quite readable and suitable for a lot of tasks.

I don't think these are readable - and hence not debuggable. You'll need extensive test cases. Regex are not great at password strength type rules because of the way elements are optional at any position. In turn, differences between regex implementations make these less portable than you'd hope: what works in Javascript might not work in Perl, and you're faced with a difficult conversion process.

I think this sort of thing is better served by being built from explicit functions (which could themselves use regex):

const hasUppercaseLetter = (word) => !!word.match(/[A-Z]/);
const hasNumber = (word) => !!word.match(/[0-9]/);
// etc.

// Testy
const passwordIsArbitrarilyStrongEnough = hasNumber(password) && hasUppercaseLetter(password);
Enter fullscreen mode Exit fullscreen mode

Totally ignoring whether password strength rules such as this are the "right" choice, when the client turns around and says they need uppercase characters to include those with accents, or that they need to have at least TWO special characters in them, you're going to have a hard time maintaining the regex.