5

I've got this RegEx which is used to validate what the user enters

It must be a value 8 - 16 characters long and can contain ONE of the certain special characters.

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~]).{8,16}$"

I'm not trying to show an alert if the user enters something that doesn't match the above. So a-z, A-Z, 0-9 and :;#~ are allowed but anything else shows an alert.

So Abcd1234# is OK, but if they enter Abcd1234!$ if will show the alert as ! & $ are not in the match.

I've tried adding ^ to the start of character match to try and negate them, but that didn't work.

What's the best way to do this?

4
  • 1
    You mean you want to only allow the chars mentioned in the lookaheads? /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~])[\da-zA-Z:;#~]{8,16}$/? Commented Jul 11, 2017 at 9:55
  • can contain or must contain ??? your regex ensures it must have A-Z but you said abcd1234# is ok Commented Jul 11, 2017 at 9:58
  • 1
    Why should abcd1234# match if you require an uppercase ASCII letter? It should not match. Commented Jul 11, 2017 at 10:01
  • the input needs to be 8-16 characters long, MUST contain lower AND upper case letters, digits and any of the special characters. Anything else should show the alert. Commented Jul 11, 2017 at 10:01

1 Answer 1

2

It seems you only need to allow the characters mentioned in the lookaheads, create a character class with them and replace the last . with it:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~])[\da-zA-Z:;#~]{8,16}$/
                                            ^^^^^^^^^^^^^^

See the regex demo

The [\da-zA-Z:;#~]{8,16} pattern will match 8 to 16 chars that are either digits, ASCII letters, or :, ;, # or ~ symbols.

Details:

  • ^ - start of string
  • (?=.*\d) - there must be a digit after any 0+ chars other than line break chars (a (?=\D*\d) will be more efficient as it is based on the contrast principle)
  • (?=.*[a-z]) - - there must be an ASCII lowercase letter after any 0+ chars other than line break chars (a (?=[^a-z]*[a-z]) will be more efficient)
  • (?=.*[A-Z]) - there must be an ASCII uppercase letter after any 0+ chars other than line break chars (a (?=[^A-Z]*[A-Z]) will be more efficient)
  • (?=.*[:;#~]) - there must be a :, ;, # or ~ after any 0+ chars other than line break chars (you may also use (?=[^:;#~]*[:;#~]))
  • [\da-zA-Z:;#~]{8,16} - 8 to 16 chars defined in the character class
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this seems to do what I need. is there a site which will break this down and explain what it all means ?
Sorry missed that. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.