phpretard Posted March 24, 2009 Share Posted March 24, 2009 I got this up to: min 8 max 20 must be numbers and letter I need at least one Uppercase letter and can't figure it out... function validate_password($password, $min_char = 8, $max_char = 20) { $password = trim($password); $eregi = eregi_replace('([a-zA-Z0-9_]{'.$min_char.','.$max_char.'})', '', $password); if(empty($eregi)) { return true; } else { return false; } } Thank you for your help! Quote Link to comment Share on other sites More sharing options...
rhodesa Posted March 24, 2009 Share Posted March 24, 2009 comments in code <?php function validate_password($password, $min_char = 8, $max_char = 20) { //$password = trim($password); Don't trim the password...if there is a space at the beginning/end, it should fail $regex = sprintf('/^\w{%d,%d}$/',$min_char,$max_char); if(!preg_match($regex,$password)) return false; //There is an invalid character or it's the wrong length if(!preg_match('/[A-Z]/',$password)) return false; return true; } print validate_password('bad') ? 'Good' : 'Bad'; print '<br />'; print validate_password('GoodPass') ? 'Good' : 'Bad'; print '<br />'; print validate_password('ThisIsTooLongOfAPassword') ? 'Good' : 'Bad'; print '<br />'; print validate_password('Invalid Char') ? 'Good' : 'Bad'; ?> so this will handle the "at least one Uppercase letter"...but do you want at least one number too? Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted March 24, 2009 Share Posted March 24, 2009 My version would be along the lines of: $numberCheck = false; $alphaCheck = false; $password = 'iuhje8Us'; // play around with this value if(preg_match('#^[a-z0-9]{8,20}$#i', $password)){ $strlength = strlen($password); for ($a = 0 ; $a < $strlength ; $a++) { if(ctype_upper($password[$a])){ $alphaCheck = true; } else if (ctype_digit($password[$a])){ $numberCheck = true; } } } if($numberCheck and $alphaCheck){ echo 'Valid password!'; // all's good! } else { echo 'Invalid password!'; // Uh-oh... invalid password } The idea is that the password must first satisfy the basic regex pattern of #^[a-z0-9]{8,20}$#i. If it does, simply go through each element of $password and check if each entry is either an uppercase character (via ctype_upper) or a number (via ctype_digit). Their respective flags ($numberCheck and $alphaCheck) are flagged as each condition is met. Finally, check to see if both flags are true.. if so, it's valid.. otherwise, it's invalid. EDIT - Addition note to OP... it is not advised to use ereg, as POSIX (ereg) will no longer be included within the core of PHP as of version 6. Future proof your code now by learning PCRE (preg). You can read up on PCRE here as well as reading the resources page. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.