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.';
}
?>