Martin C. Martin C. - 5 months ago 32
PHP Question

PHP, Regular Expression, don't allow whitespace in password

I was looking for my problem hours and hours but can't find a solution that works fine, or maybe something it's wrong with my RegEx line. I'm looking for part where user won't be allowed to put whitespace in the password. The password field must require this list of regular expressions:


  • A minimum of 1 lower case letter [a-z].

  • A minimum of 1 upper case letter [A-Z].

  • A minimum of 1 numeric character [0-9].

  • Password should not contain any special characters, symbols or spaces.

  • Passwords must be at least 8 characters in length. Maximum allowed length is 30 characters.



Right now I have generated RegEx line that include everything, but not the part with the whitespaces. If anyone know what is wrong with this line, please correct me and tell me how to fix the problem. Btw, I tried [\S] but doesn't work, I don't know why.

My RegExp line:

^(?=(?:.*[A-Z]){1,})(?=(?:.*[a-z]){1,})(?=(?:.*\d){1,})(?!(?:.*[!@#$%^&*()\-_=+{};:,<.>]))(.{8,30})$


Here is full demo of valid and non-valid passwords with this RegEx: Demo

Thanks to all that will answer and help me.

Answer

I do not know how you tried using \S, but this is exactly what you can leverage and use instead of . in the main consuming pattern:

\A                 # Start of string
  (?=[^A-Z]*[A-Z]) # Require at least one uppercase letter 
  (?=[^a-z]*[a-z]) # Require at least one lowercase letter
  (?=\D*\d)        # Require at least one digit
  (?![^!@#$%^&*()\-_=+{};:,<.>]*[!@#$%^&*()\-_=+{};:,<.>]) # No special chars
 \S{8,30}          # Match 8 to 30 non-whitespace chars
\z                 # Unambiguous end of string.

See the regex demo (the demo regex is a bit different since the test is performed against a multiline string, here is the one you should use.)

Here, I used the principle of contrast inside the lookaheads and removed unnecessary non-capturing groups.

Also, it is safer to use \z anchor to match the end of string since $ can match before the final newline in the string.

Comments