How to create custom form validation in yii 2

Rakesh Sharma      2 Comments  

A form validation in yii2 is a basic need. In yii there are many rules alredy defined but today we will be look how to create custom form validation in yii 2. After a form is submitted the input data should always be validated before taking them in use. In Yii2 we can validate the form data by using yii\base\Model::validate() function with a model as illustrated in the example below.

//Instantiate the model class
$model = new \app\models\MyForm();

// populate model attributes with user inputs
$model->load(\Yii::$app->request->post());
//validate the date being submitted the end user
if ($model->validate()) {
    // all inputs are valid
} else {
// validation failed, we can access the errors using     $error property as:
    $errors = $model->errors;
}

Declaring Rules

Before using the validate() function, the validation rules needs to be configured in the model class. This can be done by overriding the yii\base\Model::rules() method. There are number of core validatiors provided by the Yii2 which you can specify in the rules() method.Please refer to the Core Validators for the complete list of core validators available . Below is the example showing how to declare a validation rule.

public function rules()
{
    return [
        // the username and email attributes are required
        [['username', 'email'], 'required'],

        // the email attribute should be a valid email address
        ['email', 'email'],
    ];
}

As per the above example the rules() method should return an associative array containing set of rules applied to the model attributes. The each rule array should be in the following format.

[
     //The model attribute name(s).It can be specified both as an array or a string depending whether you need to apply same rule on multiple attributes.This is a compulsory field.
    ['attribute1', 'attribute2', ...],

    // This should specify rule that need to be applied to the attribute(s).
    // It can be a class name, validator alias, or a validation method name
    'validator',

    //The scenario to which the rule should be applied.This is optional.
    'on' => ['scenario1', 'scenario2', ...],

    //This is an optional field. If you want to customise the validation message to be shown to the end user, you can specify that here.
   'message'=>'The validation meesage that to be shown to the end user',

    // This field is optional. It specifies additional configurations for the validator object
    'property1' => 'value1', 'property2' => 'value2', ...
]

Creating Custom Validators in yii2

In Yii2 you can create your own validators besides the core validators. This can be achieved by two ways. First one is inline validator where you create a validation function of your own in the model itself. The second one is standalone validator where you create a validation class by extending yii\validators\Validator or its child class.

Inline Validators

An inline validator is one defined in terms of a model method or an anonymous function. The signature of the method/function is:

/**
 * @param string $attribute the attribute currently being validated
 * @param mixed $params the value of the "params" given in the rule
 */
function ($attribute, $params)

In this method you need to call the yii\base\Model::addError() function specifying the attribute and the error message that to be delivered to the end user.Please refer the examples below for more details.

use yii\base\Model;

class MyForm extends Model
{
    public $username;
    public $email;

    public function rules()
    {
        return [
            // an inline validator defined as the model method validateUsername()
            ['username', 'validateUsername'],

            // an inline validator defined as an anonymous function
            ['email', function ($attribute, $params) {
                if (!filter_var($this->$attribute, FILTER_VALIDATE_EMAIL)) {
                  $this->addError($attribute, 'The email format is invalid!');
                }
            }],
        ];
    }

    public function validateUsername($attribute, $params)
    {
        if (preg_match('/[^a-z])/i', $this->$attribute)) {
             $this->addError($attribute, 'Username should only contain alphabets');
        }
        if ( ! preg_match('/^.{3,8}$/', $this->$attribute) ) {
             $this->addError($attribute, 'Username must be bwtween 3 to 8 characters.');
        }
    }
}

Standalone Validators

A standalone validator is a class extending yii\validators\Validator or its child class. The validation logic can be written by overiding the yii\validators\Validator::validateAttribute() method. If an attribute fails the validation, call yii\base\Model::addError() to save the error message in the model.

We are going to create the standalone version of the “validateUsername” validator as illustrated in the inline validators section. Below example shows how the standalone version of the same validators should look like.

namespace app\components;

use yii\validators\Validator;

class UsernameValidator extends Validator
{
    public function validateAttribute($model, $attribute)
    {
        if (preg_match('/[^a-z])/i', $model->$attribute)) {
             $this->addError($model,$attribute, 'Username should only contain alphabets');
        }
        if ( ! preg_match('/^.{3,8}$/', $model->$attribute) ) {
             $this->addError($model,$attribute, 'Username must be bwtween 3 to 8 characters.');
        }
    }
}

Now in the model it can be used as :

public function rules()
    {
        return [
            .....
            ['username', app\components\UsernameValidator::className()],
            .....
        ];
    }

Hope you have liked the article.For more information regarding how to create custom form validation in yii 2 or input validation please visit Yii2 official site.

  • максим

    Nice!

  • manoj saini

    Great,

    I need to create custom validation.i saw a lot example but this one helped me.Really appreciate.
    Thanks rakesh