0

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

4
  • This doesn't lend itself to a clean regular expression. It'll have to be very much brute-force. Commented May 30, 2017 at 4:50
  • Can you clarify your question? It echoes ok for both 12Hello and Hello12, unless you're doing something other than what or in addition to you've posted. Here's a working demo. By the way, please try formatting your code before posting. The code you posted is difficult to read, which leads to errors.
    – elixenide
    Commented May 30, 2017 at 4:53
  • There are good examples on this question - stackoverflow.com/questions/19605150/…
    – ASR
    Commented May 30, 2017 at 4:53
  • 1
    Please stop doing this in 2017 - allow arbitrary input, and then hash to the desired password length. Just use a library that tells your users how easy it is to hack their password (ideally, of the "this password can be cracked in 2 seconds, please pick a better one") and then accept whatever the hell they pick that is strong enough. There is literally no reason to roll your own code here, we already figured this out for you, in your favourite language, use that. Commented May 30, 2017 at 4:56

2 Answers 2

3

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.

2

Try this one:-

Minimum 6 character

Atleast 1 uppercase character

At least one digit

Expression:

"/^(?=.*?[0-9])(?=.*[A-Z]).{6,12}$/"
3
  • 1
    After the edits this answer is now the same as mine, although lacking a description.
    – chris85
    Commented May 30, 2017 at 5:00
  • Sorry chris,when i post my answer..really i didnt check your answer above. Commented May 30, 2017 at 5:02
  • The ? here .*? is redundant. * is 0 or more anyway.
    – fubar
    Commented May 30, 2017 at 5:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.