Fetz
Fetz

Reputation: 53

regex for password 6-12 chars one digit, one uppercase

I'm trying to check user password with this regular exp:

$regex='/^(?=.*[A-Za-z0-9@])(?=.*\d)[a-zA-Z0-9@]{6,12}$/';

if(isset($_POST['password']) && strlen($_POST['password'])>=6 && 
strlen($_POST['password']<=12) && preg_match($regex, $_POST['password'])){

echo 'ok';
}else{echo 'invalid password';}

I'd like the password to be from 6 to 12 chars, at least one digit and at least one Uppercase.

It doesn't work if the password is something like 12Hello instead it works with Hello12 , someone could please help?

Thanks

Upvotes: 0

Views: 1974

Answers (2)

chris85
chris85

Reputation: 23880

Your character class is too broad. You need to check for things separately.

^(?=.*[A-Z])(?=.*\d).{6,12}$

(?=.*[A-Z]) is at least one upper case character.
(?=.*\d) is at least one number
and .{6,12} is 6-12 characters (that aren't new lines)
The ^$ are anchors ensuring the full string matches.

In your regex your character class [A-Za-z0-9@] allows an uppercase character, lowercase, number, or @ (which doesn't ensure you have 1 uppercase character). You also don't need the strlen functions if using this regex.

Upvotes: 3

Arshad Shaikh
Arshad Shaikh

Reputation: 564

Try this one:-

Minimum 6 character

Atleast 1 uppercase character

At least one digit

Expression:

"/^(?=.*?[0-9])(?=.*[A-Z]).{6,12}$/"

Upvotes: 2

Related Questions