2

I have regex for validating user passwords to contain:

  • atleast 8 alpha numberic characters
  • 1 uppercase letter
  • 1 lowercase letter
  • 1 digit

Allowed special charaters !@#$%*.~

I am using the following regex:

(?=(.*\w){8,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})(?=(.*[0-9]){1,})(?=(.*[!@#$%*.~]))

This however does not prevent the user from entering other special characters such as <,> , &.

How do I can restrict the allowed number of special characters?

3
  • 3
    A regular expression is probably not a good way to check for this. Also, restricting the special characters allowed doesn't do anything but make adding them meaningless, since the password strength is a function of the alphabet size. The fact that you're restricting them almost implies you're storing them in a database in plain text, but I'm sure you're not doing that. Commented Oct 2, 2012 at 18:02
  • 2
    Let them enter anything, don't restrict the set of characters. I absolutely HATE when I can't use a stronger password because a - isn't allowed. Why shouldn't I be allowed to use '"-()[]&<>^_+= etc in my password? Commented Oct 2, 2012 at 18:21
  • 1
    Agreed - you should validate that they have met a minimum standard for password strength, but not limit the strength of the passwords that they can use. Commented Oct 2, 2012 at 19:47

2 Answers 2

3

A single regex to validate everything will ultimately look like line noise.

Instead I suggest:

  • Use simple String functions to test length
  • Use Regex to test for character inclusion and validity
Sign up to request clarification or add additional context in comments.

Comments

1
^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])[a-zA-Z0-9!@#$%*.~]{8,}$

The anchoring (^ and $) is important, by the way.

Comments

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.