Showing posts with label password strength. Show all posts
Showing posts with label password strength. Show all posts

Tuesday, November 8, 2011

Create your own Validation Rule

Some times the core validation rules provided by Yii won't satisfy all your needs, so you'll need to create your very own validation rule.

Easy approach: inside-model rule

The easiest way to create a new validation rule is inside the model that is going to use it.
Let's say that you want to check if a user password is safe enough.
Usually you could achieve this result just by using the CRegularExpressionValidator but for the sake of this guide let's pretend that validator does not exist.
first of all in your model class you'll have to add two constants
const WEAK = 0;
const STRONG = 1;
then in your rules method you'll have to set the rule
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
       array('password', 'passwordStrength', 'strength'=>self::STRONG),
    );
}
make sure that you won't give the rule the name of an existing one, otherwise you are going to have some troubles later.
Now the only thing you need to do is create a new method inside the model, named after the validation rule you just declared.
/**
 * check if the user password is strong enough
 * check the password against the pattern requested
 * by the strength parameter
 * This is the 'passwordStrength' validator as declared in rules().
 */
public function passwordStrength($attribute,$params)
{
    if ($params['strength'] === self::WEAK)
        $pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';  
    elseif ($params['strength'] === self::STRONG)
        $pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';  
 
    if(!preg_match($pattern, $this->$attribute))
      $this->addError($attribute, 'your password is not strong enough!');
}
The new method you just created accepts two arguments:
  • $attribute = is the name of the attribute that the method is validating
  • $params = additional parameters that you could define in the rules
In our rules method we used this rule on the password attribute, so the value of attribute inside our validation model will be password
In the rule we also setted an additional parameter named strength
the value of that parameter will be inside the $params array
As you can see inside the method we are making a call to CModel::addError().
Add Error accepts two parameters: the first one is the name of the attribute that you want to display the error in your form, the second one is the actual error string you want to be displayed.

Complete approach: extending the CValidator class

If you need your custom validation rule in more then one model the best thing to do is extending the CValidator class.
Extending this class you also can take advantage of other features, like CActiveForm::$enableClientValidation, first implemented with Yii 1.1.7 release.

Creating the class file

The first thing that you have to do is create your class file. The best thing is to always name it after your class name, to best use Yii lazy loading feature. Let's create a new directory inside your application extensions directory (which is located inside the protected directory).
Name this directory MyValidators.
Then we create our own file: passwordStrength.php
Inside this file create our CValidator class
class passwordStrength extends CValidator
{
 
    public $strength;
 
    private $weak_pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';
    private $strong_pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';
...
In the class file create one attribute for each additional parameter that you want to use inside your validation rule.
CValidator will take care to populate that attribute with the parameter value all by itself.
We also created two other attributes, each containing the patterns we want to use in our preg_match function.
Now we have to override the parent abstract method validateAttribute
/**
 * Validates the attribute of the object.
 * If there is any error, the error message is added to the object.
 * @param CModel $object the object being validated
 * @param string $attribute the attribute being validated
 */
protected function validateAttribute($object,$attribute)
{
    // check the strength parameter used in the validation rule of our model
    if ($this->strength == 'weak')
      $pattern = $this->weak_pattern;
    elseif ($this->strength == 'strong')
      $pattern = $this->strong_pattern;
 
    // extract the attribute value from it's model object
    $value=$object->$attribute;
    if(!preg_match($pattern, $value))
    {
        $this->addError($object,$attribute,'your password is too weak!');
    }
}
The method above is self explanatory i think.
Of course you could use constants in those IF, and I actually recommend it.

Implementing Client Validation

If you want to implement client validation you'll need to override another method inside your class: clientValidateAttribute
/**
 * Returns the JavaScript needed for performing client-side validation.
 * @param CModel $object the data object being validated
 * @param string $attribute the name of the attribute to be validated.
 * @return string the client-side validation script.
 * @see CActiveForm::enableClientValidation
 */
public function clientValidateAttribute($object,$attribute)
{
 
    // check the strength parameter used in the validation rule of our model
    if ($this->strength == 'weak')
      $pattern = $this->weak_pattern;
    elseif ($this->strength == 'strong')
      $pattern = $this->strong_pattern;     
 
    $condition="!value.match({$pattern})";
 
    return "
if(".$condition.") {
    messages.push(".CJSON::encode('your password is too weak, you fool!').");
}
";
}
As you can see this method simply returns the javascript that you need to use for your validation

Last step: how to use your validation class inside the module rules

There are several approach you can use here.
You could first use Yii::import in the rules method before returning the rules array, or you can just use Yii dot notation:
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
       array('password', 'ext.MyValidators.passwordStrength', 'strength'=>self::STRONG),
    );
}

Jquery password strength

Password Strength MeterThese quick password strength meter scripts are meant to help users learn how to create stronger passwords and implement password strength checking in their web forms. For membership websites, registration forms are one of the most important parts. Implemention of a password strength meter will not only help your users create strong password but also the first step where you can show that you care about the security of the website & all the data collected. Password strength checking improve the security of the website so that weak passwords are not allowed to be used that may have unwanted consequences.
Guiding users to have a strong password with the help of password strength meters, besides being an easy process, will help improving the security of the whole & show that the website pays attention to it. antalya web tasarım / web tasarım

Here are 10 password strength meter scripts for a better registration interface:

  1. Password Meter is a JavaScript function that checks the strengths of passwords with a well-defined algorithm and their website nicely displays how the strength is calculated.

  2. Ultimate Password Strength Meter
    The ultimate password strength meter is an improved version of this script. It that has a graphical interface (uses Prototype & Script.aculo.us) that shows the strength of the password entered.

  3. Yet Another Password Meter

    Based on the PasswordMeter script, YAPM is an improved version which enables you to measure the strength of your passwords and use the functions inside to adapt in your websites.

  4. jQuery Password Strength Meter
    Password Strength Meter is a jQuery plug-in that provides a smart algorithm to detect a password's strength.
    JavaScript Password Strength Meter
    With the help of regular expressions that checks the repeated characters, uppercase-lowercase usage, the string length & more, this password meter script generates a score for the password.
  5. How to Make a Password Strength Meter Like Google?
    Based on the code here, this is a JavaScript password meter. It displays the result with a color bar & an information text.
  6. jQuery Password Strength Meter Plugin
    This jQuery plugin calculates the password strength similar to th other solutions like checking the repeated characters, amount of numbers, special characters used, etc. But with a difference takes into consideration the username value too.
  7. Password Strength Field (A jQuery Plugin)
    Using the Password Strength Field plugin, you can instantly add this functionality to a password field. It can be configured to have a custom "point system" where every variable can be defined.
  8. PHP Password Strength Meter
    detailed tutorial on creating an Ajaxed password meter with PHP. This script checks the input at the server-side rather client-side. A JSON result (strength value) is returned from the Ajax request and according to that value, the strength of the password is displayed.

    Password Strength Meter With ExtJS

    This script is built with Ext JS framework and displays the password strength with an animated bar.