0

The pattern should match when there is at least 1 numeric OR 1 special character AND a total length of 8 or more.

It partially works but only if the special character or numeric values are at the beginning.

So far I have:

/([\d]|[!@#$%^&*()_+])([a-z]).{8,}/
Adrian
  • 353
  • 2
  • 7
  • 20
  • 1
    Just so you know, `[A-z]` also contains the characters ``[\]^`_`` – Patrick Roberts Jul 20 '16 at 04:48
  • Good point, thanks will drop it to a-z. – Adrian Jul 20 '16 at 04:49
  • Possible duplicate of [Regex for Password Must be contain at least 8 characters, least 1 number and both lower and uppercase letters and special characters](http://stackoverflow.com/questions/19605150/regex-for-password-must-be-contain-at-least-8-characters-least-1-number-and-bot) – Alex Kudryashev Jul 20 '16 at 04:53
  • *"only if the special character or numeric values are at the beginning."* - Because you are only checking them at the beginning `([\d]|[!@#$%^&*()_+])` is the first character only, then `([a-z])` is the second. Then `{8,}` is only for the `.` – Spencer Wieczorek Jul 20 '16 at 04:55
  • @SpencerWieczorek I'm pretty sure he already knows and understands that, but just doesn't know how to specify what he wants – Patrick Roberts Jul 20 '16 at 04:57
  • That's ok. Appreciate the help, every time I work with regex I regret not giving it more attention. – Adrian Jul 20 '16 at 05:37

2 Answers2

3

Why overcomplicate a RegExp? Sure it's possible, but you have to specify every permutation of possible combinations of characters that match those requirements. Just do this:

if (/[\d!@#$%^&*()_+]/.test(string) && string.length >= 8) { ... }
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
0

You're doing it backwards, don't try to positively match special characters, that limits what people can/must use. Instead, match something you consider to be not not special, e.g.:

pw.length >= 8 && /\d/.test(pw) && /[^a-z\d\x20]/i.test(pw)

Than checks length, presence of a digit, then presence of a character that's not alphanumeric nor a space (the i flag makes it case-insensitive). You may also want to disallow spaces and other control characters that are not usually able to be typed on a keyboard (prevents people pasting in junk):

&& !/[\x00-\x20]/.test(pw)
Walf
  • 8,535
  • 2
  • 44
  • 59