BDD BDD - 4 months ago 5x
Javascript Question

Why are my optional characters not being caught?

I'm trying to create a regex to test passwords against. My current one checks for the following:

  • One Uppercase Letter

  • One Lowercase Letter

  • One number

Currently, the user can't enter special characters, however I'm trying to add that as an optional check (so Testing1 and Testing1! should both match). I've tried:


But it doesn't catch it. I have a feeling my special character set is in the wrong place, but I'm not sure where to place it.

Where do I add my list of special characters as optional checks?


There's many ways that you can set up your regex, such as creating a whitelist, or a blacklist, for types of characters. This one in particular creates a whitelist for characters that can be used which seems to be what you are looking for.


Regex Breakdown:

^ // Assert position at start of the line
(?=.*[A-Z]) // First positive lookahead, makes sure a capital character exists
(?=.*[a-z]) // Make sure a lowercase character exists
(?=.*[0-9]) // Make sure a number exists
[A-Za-z0-9$@$!%*#?&] // All of the possible characters that can be typed
{8,} // 8 to infinity characters
$ // Assert position at end of line

Since you say that you want special characters as optional, they are just placed in the possible characters that can be typed, but they are not validated by any positive lookaheads.

See this regex in action on regex101. Keep in mind, the modifiers gm are there to validate across lines in this example and should probably be removed in your use case.

Unless of course you have reasons for the "whitelist" approach, a more common approach is to allow almost anything (blacklist), and then validate that a certain criteria is met.