Validate (input) password
Posted on August 30, 2008, Filled under PHP,
Bookmark it
This is a useful function if you need to validate a password (input). If you have a form and you need to check if the username, which is registering, entered a valid password (without illegal characters) then this would help you to do it. Only letters, numbers and underscores are accepted.
<?php
/*
Credits: http://www.bitrepository.com/
*/
// default chars values are defined
function validate_password($password, $min_char = 4, $max_char = 20)
{
// Remove whitespaces from the beginning and end of a string
$password = trim($password);
// Accept only letters, numbers and underscore
$eregi = eregi_replace('([a-zA-Z0-9_]{'.$min_char.','.$max_char.'})',
'', $password);
if(empty($eregi))
{
return true;
}
else
{
return false;
}
}
$password = 'my_password_123';
/*
First parameter: Password
Second parameter: Minimum chars
Third parameter: Maximum chars
*/
$validator = validate_password($password, 4, 20);
if($validator)
{
// Our current example will return true
echo 'The password is valid.';
}
else
{
/* if our password value is for instance: my_@#%_password
our function will return false */
echo 'The password appears to be invalid.
It should contain only letters, numbers and underscore.';
}
?>
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- August 30, 2008
- article by Gabriel C.
- 2 comments
Related Posts
Validate (input) usernameat August 29, 2008 with 2 comments
PHP: How to validate e-mail addresses using regular expressionsat May 21, 2008 with 2 comments
How to generate a random password in PHPat August 29, 2008 with 2 comments
PHP: How to validate a telephone numberat September 24, 2008 with 1 comment
Validate numeric stringat May 21, 2008

2 Replies to "Validate (input) password"
January 26, 2009 at 5:42 PM
If you encrypt your password before introducing it on a database you won't need any validation, and so the password will be stronger because they can have numbers, letters and symbols.
January 29, 2009 at 7:36 AM
João, this function just checks if the password has a specific format (a minimum and maximum characters length, letters, numbers or underscore). The "password" field should not be left unchecked even though the password will be encrypted when introducing it in the database.