...

View Full Version : Simple regular expression question



AlexV
09-15-2009, 10:45 PM
I need a condition to validate password entered in an HTML form (when user registers).

- Password must be between 8 and 20 chars.
- Password must at least contain a letter AND at least one non-letter (space, punctuation, number...)

So far I have:


if (
strlen($_POST['password']) < 8 ||
strlen($_POST['password']) > 24 ||
ereg("[a-zA-Z]+", $_POST['password']) /* Only letters = bad */ ||
eregi("[^0-9]", $_POST['password']) /* Only numbers = bad */
)
{
//Password bad!
}

I'm really not sure about my "ereg"... The "only letters" one seems OK but the "only numbers" one seems bad...

Anyone can help?

Thanks!

SKDevelopment
09-16-2009, 12:10 AM
I think something like this (not checked):


$password = trim($_POST['password']);
if (
strlen($password) < 8 ||
strlen($password) > 24 ||
preg_match("/^([a-z]+|\d+)$/i", $password)
)
{
//Password bad!
}

Please notice that I have used preg_match() (http://php.net/preg_match) instead of eregi(). It is better to use PCRE, not POSIX regular expressions. POSIX regular expressions are going to be moved to PECL as far as I know. Also PCRE functions are often faster. And as far as I remember (maybe I am wrong) POSIX regular expression functions are not binary safe.

Edit: I think I should give a brief explanation on the pattern "/^([a-z]+|\d+)$/i":
^ - matches beginning of the string
$ - matches end of the string
() - used for grouping
| means "or"
\d means a digit from 0 to 9
i after "/" makes the regexp case-insensitive
So this regexp means: either only letters from a to z in any case or only digits.

Coyote6
09-16-2009, 01:51 AM
Please notice that I have used preg_match() (http://php.net/preg_match) instead of eregi().


Definitely use preg_match... they are getting rid of the ereg functions in PHP 6 if I remember right. I just recently went through a lot of my old code and changed all of mine. Then I found a couple that I had missed last night. Boy was that fun... hehehe :p

AlexV
09-16-2009, 02:20 PM
preg_match("/^([a-z]+|\d+)$/i", $password)

is not totally working... The password "foo bar" (without quotes) is valid (since it contain letter and non letter - space) but the regexp dosen't let it pass... Any idea why?

SKDevelopment
09-16-2009, 02:31 PM
It is not the regexp. The code:


$password = 'foo bar';
if (
strlen($password) < 8 ||
strlen($password) > 24 ||
preg_match("/^([a-z]+|\d+)$/i", $password)
)
{
echo 'Bad password';
} else {
echo 'Good password';
}

outputs 'Bad password' because the length of the string is 7 which is less than 8. If you remove "strlen($password) < 8", the password would be considered as good.

AlexV
09-16-2009, 04:17 PM
Hahaha I missed that the regexp seems ok thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum