1

I'm trying to create a simple regex checker for username, password and email validation.

The requirements are as follows:

username:

- Only letters and numbers (a-z, A-z, 0-9). 
- No spaces, linebreaks, tabs or special characters.
- At least 5 characters in length.
- No more than 20 characters in length.

Password:

- At least 8 digits in length.
- no more than 40 characters in length.
- Must contain at least 1 special character or number.

Email:

- Must follow the format "value@value.com".

This is what I have so far:

Username - working.

$username = $enteredUsername;
if(preg_match('/^[a-zA-Z0-9]{5,30}+$/', $username) == false ) {

echo "the username is invalid";

}

Password: not working yet:

$password = $enteredPassword;
if(preg_match('/^[a-zA-Z0-9]+[\w0-9]{8,}+$/', $password) == false ) {

echo "the password is invalid";

}

Email - working.

$email = $enetered email.
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) {

    echo "the email is invalid";
} 

The email and username works, but I can't seem figure out the correct regex for the password.

user3143218
  • 1,738
  • 5
  • 32
  • 48
  • why would you want a regex for your passwords just use prepared statements if you want to prevent sql-injections – kpp May 01 '14 at 08:25
  • All my sql queries get auto-prepared in DB connection setup. This is about ensuring a user provides a strong password, not sql injection. – user3143218 May 01 '14 at 08:30
  • Just require a minimum length and let the rest up to the user. – Gumbo May 01 '14 at 08:31
  • yeah like gumbo said I would put up like 3 or 4 checks first check if password character count is more than 16 its strong enough, if its less add special characters or numbers and if its less than 10 not allowed. why build a fully regex if you can do it easier – kpp May 01 '14 at 08:33
  • So a series of if else... – user3143218 May 01 '14 at 08:36
  • 1
    possible duplicate of [Regex for password PHP](http://stackoverflow.com/questions/8141125/regex-for-password-php) – Amal Murali May 01 '14 at 08:41
  • @AmalMurali [The only secure password is the one you can’t remember](http://www.troyhunt.com/2011/03/only-secure-password-is-one-you-cant.html) – SilverlightFox May 02 '14 at 09:13

1 Answers1

1

For the password regex, try:

^(?=.*[^a-zA-Z]).{8,40}$

This uses a positive lookahead that excludes alphabetic characters to ensure a special character or number is included.

Calvin
  • 468
  • 3
  • 7