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

Fetz
  • 53
  • 1
  • 9
  • This doesn't lend itself to a **clean** regular expression. It'll have to be very much brute-force. – Arya McCarthy May 30 '17 at 04: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](https://3v4l.org/N4FVL). By the way, please try formatting your code before posting. The code you posted is difficult to read, which leads to errors. – elixenide May 30 '17 at 04:53
  • There are good examples on this question - https://stackoverflow.com/questions/19605150/regex-for-password-must-be-contain-at-least-8-characters-least-1-number-and-bot – ASR May 30 '17 at 04: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*. – Mike 'Pomax' Kamermans May 30 '17 at 04:56

2 Answers2

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.

chris85
  • 23,846
  • 7
  • 34
  • 51
2

Try this one:-

Minimum 6 character

Atleast 1 uppercase character

At least one digit

Expression:

"/^(?=.*?[0-9])(?=.*[A-Z]).{6,12}$/"
Arshad Shaikh
  • 564
  • 1
  • 3
  • 13