Is it considered best practice to break up a regex for password verification?

For example if I want to check a password to have at least one lowercase letter, one uppercase letter, one digit and one special character. Is it better to do something like

if (\[a-z]\.test(password) && \[A-Z]\.test(password) && \[0-9]\.test(password) && \[!@#\$%\^&*].test(password))

rather than one long single regex?

I would go with one long regex. Your regex should do a thing regardless of how complex said thing is. Multiple small regex are also probably more time consuming than one long regex that does the same thing

Typically, you would write a single regex when you can.

It depends what you want to do. If you just want to say “this is wrong”, then one is fine, and most of the time just having that’s perfectly ok. And that’s just the HTML pattern attribute on an input.

If you want something where you have an input with multiple messages attached to it (your password must have x, y and z…), and they reflect the current state, then yeah you need multiple patterns. But you also need JavaScript logic to check what’s been typed so far and which patterns it matches/fails to match. It’s a lot more complex, normally only used for inputs where it’s extremely important that the user gets feedback and it’s worth all the extra code

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.