Validate (input) password

Posted on August 30, 2008, Filled under PHP,  Bookmark it

Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.

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!

Get our RSS Feed!

Sponsors

Related Posts

2 Replies to "Validate (input) password"

  1. 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.

  2. 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.

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled