Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top