Validation Rules for model attributes In Yiiframework 2.0

After submitting the form data, We have to validate the input data information before we start to use. We can validate the inputs by calling the [[yii\base\Model::validate()]] method of yii2.0.

Yii2.0 is giving the support for this data validation and also it is very easy way to test the input data. To check validate() of input data, we should declare validation rules for the attributes you plan to validate. The rules should be an array and returned to base class of [[yii\base\Model::validate()]]. Each and every rule must have atleast one attribute. We can create custom new rule based on our business criteria. We added the list of validation from Yiiframework 2.0

Data Type Validation In Yii2.0

......
public function rules(){
	return [
		[['boolean_var'],'boolean'],
		[['number_min'],'number'],
		[['integer_var'],'integer'],
		[['double_var'],'double'],
		[['string_var'],'string'],
	];
}
......

Required Validation In Yii2.0

......
public function rules(){
	return [
		[['username'],'required'],
		[['password', 'email', 'phoneno'], 'required'],
	];
}
......

Assigning Default Value In Yii2.0

......
public function rules(){
	return [
		// set "email" as null if they are empty
		[['email'],'default'],
		// set "level" to be 111 if it is empty
		[['level'],'default','value'=>'111'],
	];
}
......

Minimum, Maximum Number Validation In Yii2.0

......
public function rules(){
	return [
		[['number_min'],'number','min'=>10],
		[['number_max'],'number','max'=>100],
		[['number_min_max'],'number','min'=>10,'max'=>100],
	];
}
......

Minimum, Maximum String Validation In Yii2.0

......
public function rules(){
	return [
		[['min_string'],'string','min'=>10],
		[['max_string'],'string','max'=>10],
		[['min_max_string'],'string','min'=>5,'max'=>10],
		['min_max_string2', 'string', 'length' => [4, 10]],
	];
}
......

File Type/ Image Validation In Yii2.0

......
public function rules(){
	return [
		[['file_image'],'image'],
		[['file_var'],'file','types'=>['gif','jpg']],
		['file_image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 
				'maxSize' => 1024*1024],
		['file_image', 'image', 'extensions' => 'png, jpg, gif',
				'minWidth' => 100, 'maxWidth' => 500,
				'minHeight' => 100, 'maxHeight' =>500,
		],

	];
}
......

Date Format Validation In Yii2.0

......
public function rules(){
	return [
		[['date_var'],'date', 'format'=>'d-m-yy'],
		[['from_date', 'to_date'], 'default', 'value' => null],
		[['from_date', 'to_date'], 'date'],

	];
}
......

Email, URL Format Validation In Yii2.0

......
public function rules(){
	return [
		['email_var','email'],
		['url_var','url'],
		//prepend the 'http' with url if it is not available 
		['website', 'url', 'defaultScheme' => 'http'],
	];
}
......

Unique Validation In Yii2.0

......
public function rules(){
	return [
		[['unique_var'],'unique'],
		[['email'], 'unique']
		//email is validated in secondary_email column
		['email', 'unique', 'targetAttribute' => 'secondary_email'],


		// need unique together, both will receive error message
		[['email', 'secondary_email'], 'unique', 'targetAttribute' => ['email', 'secondary_email']],
		[['lastname','firstname'], 'unique', 'targetAttribute' => ['firstname','lastname']],

		// need unique together, but email only will receive error message
		['email', 'unique', 'targetAttribute' => ['email', 'secondary_email']],
		// (email) and secondary_email in email (using a1 value)
		['user_name', 'exist', 'targetAttribute' => ['email', 'secondary_email' => 'email']],

	];
}
......

exist Validation In Yii2.0

['user_name', 'exist'],
//email should not be exist in secondary_email
['email', 'exist', 'targetAttribute' => 'secondary_email'],
//sound likes composite primary key
[['user_name', 'email'], 'exist', 
		'targetAttribute' => ['user_name', 'email']],

// user_name needs to exist by checking the existence of ...
// (email) and secondary_email in email (using a1 value)
['user_name', 'exist', 
		'targetAttribute' => ['email', 'secondary_email' => 'email']],
//find exist email in secondary_email
['user_name', 'exist', 
		'targetAttribute' => ['email' => 'secondary_email']],

Filter Validation In Yii2.0

......
public function rules(){
	return [				
		[['filter_trim'],'filter','filter'=>'trim'],
		[['filter_trim'],'filter','filter'=>'strtolower'],
		['filter_custom_function', 'filter', 'filter' => function ($value) {
			// your concept
			if($value=='')
				return '';
			return 'Value Changed';
		}],
	];
}
......

Range In Validation In Yii2.0

......
public function rules(){
	return [
		['range_in_min_max', 'in','range'=>range(5,20)],
		['range_in','in','range'=>['en','fr','zn']], ,'strict'=>false/
		['range_in_string','in','range'=>['EN','FR','ZN'],'strict'=>true],
	];
}
......

Compare Validation In Yii2.0

compareAttribute: It would be the name of the attribute suffixed with _repeat.
compareValue : A constant value , it should be compared with input value.
operator : What type of condition we have to check They are ‘==’,’===’,’>’,’>=’,’<','<=', '!=','!==' Ex: Compare Password And Confirm Password

……
public function rules(){
	return [
		[[‘passwordConfirm’], ‘compare’, ‘compareAttribute’ => ‘password’],		
		// validates if the value of “password” attribute equals to that of “password_repeat”
		[‘password’, ‘compare’],//password_repeat

		[‘age’, ‘compare’, ‘compareValue’ => 18, ‘operator’ => ‘>=’],

		[[‘password’,’date_var’],’safe’],
	];
}
……

Custom Validation In Yii2.0

......
public function rules(){
	return [
		['custom_validation','custom_function_validation', 'values'=>['One', 'Two']],
	];
}
public function custom_function_validation($attribute, $params){
	// add custom validation
	if (!in_array($this->$attribute, $params['values'])) 
		$this->addError($attribute,'Custom Validation Error');
}
......

Inline Custom Validation In Yii2.0

......
public function rules(){
	return [
		['token', function ($attribute, $params) {
			if (!ctype_alnum($this->$attribute)) {
				$this->addError($attribute, 'The token must contain letters or digits.');
			}
		}],
	];
}
......

captcha Validation In Yii2.0

......
public function rules(){
	return [
		// set captcha validation
		['verificationCode', 'captcha'],
	];
}
......

match Validation In Yii2.0

['user_name', 'match', 'pattern' => '/^[a-z]\w*$/i']

Full Test Validation Model

<?php
namespace app\models;
class Testmodel extends \yii\db\ActiveRecord
{
	/** Declare class varibles**/
	/** boolean values **/
	public $boolean_var;
	
	public $default_value;
	
	/** number values **/
	public $integer_var;
	public $double_var;
	public $number_min;
	public $number_max;
	public $number_min_max;
	
	/** string values **/
	public $min_string;
	public $max_string;
	public $min_max_string;
	public $min_max_string2;
	
	/** date values **/
	public $date_var;
	
	/** Email And URL values **/
	public $email_var;
	public $url_var;
	
	public $unique_var;
	
	/** Range values **/
	public $range_in_min_max;
	public $range_in;
	public $range_in_string;
	
	/** Password values **/
	public $password;//error
	public $passwordConfirm;//error
	
	/** File values **/
	public $file_image;
	public $file_var;
	
	public $custom_validation;
	
	/** Filter values **/
	public $filter_trim;
	public $filter_custom_function;
	
	
	
	
	public function rules(){
		return [
        [['boolean_var'],'boolean'],
		[[ 'range_in_string'],'required'],
		
		[['default_value'],'default','value'=>'DEFAULT VALUE'],
		
		[['integer_var'],'integer'],
		
		[['double_var'],'double'],
		
		[['number_min'],'number','min'=>10],
		[['number_max'],'number','max'=>100],
		[['number_min_max'],'number','min'=>10,'max'=>100],
		
		[['file_image'],'image'],
		[['file_var'],'file','types'=>['gif','jpg']],

		[['date_var'],'date', 'format'=>'d-m-yy'],

		
		[['min_string'],'string','min'=>10],
		[['max_string'],'string','max'=>10],
		[['min_max_string'],'string','min'=>5,'max'=>10],
		['min_max_string2', 'string', 'length' => [4, 10]],

		
		['email_var','email'],
		['url_var','url'],
		
		[['unique_var'],'unique'],
		
		[['filter_trim'],'filter','filter'=>'trim'],
		[['filter_trim'],'filter','filter'=>'strtolower'],
		['filter_custom_function', 'filter', 'filter' => function ($value) {
				// your concept
				if($value=='')
					return '';
				return 'Value Changed';
		}],

		['range_in_min_max', 'in','range'=>range(5,20)],

		['range_in','in','range'=>['en','fr','zn'],'strict'=>false], //strict false
		['range_in_string','in','range'=>['EN','FR','ZN'],'strict'=>true],
		
		['custom_validation','custom_function_validation'],
		
		[['passwordConfirm'], 'compare', 'compareAttribute' => 'password'],		
		[['password','date_var'],'safe'],
		];
	}
	
	public function custom_function_validation($attribute){
		// add custom validation
		$this->addError($attribute,'Custom Validation Error');
	}
	public function attributeLabels(){
		return [
			'boolean_var'=>'Boolean',
			
			'default_value'=>'Default',
			'integer_var'=>'Integer',
			'double_var'=>'Double Variable',
			'date_var'=>'Date',
			
			'custom_validation'=>'Custom',			
			
			'number_min'=>'Number Min',
			'number_max'=>'Number Max',
			'number_min_max'=>'Number Min, Max',
			
			'file_image'=>'File Image',
			'file_var'=>'File ',					
			
			'url_var'=>'URL',
			'unique_var'=>'Unique',
			'email_var'=>'Email',
			
			'min_string'=>'Minimum String',
			'max_string'=>'Maximum String',
			'min_max_string'=>'String Min L:5, Max F1 M:10',
			'min_max_string2'=>'String Min  L:4, Max F2 M:10',
			
			'range_in_min_max'=>'Range Min  L:5, Max F2 M:20',
			'range_in'=>"Range in (en, fr, zn)",
			'range_in_string'=>"Range In Strict Mode(EN, FR, ZN)",
			
			'password'=>'Password',
			'passwordConfirm'=>'Confirm Password',
			'filter_custom_function'=>'Filter Custom Function',
			'filter_trim'=>'Trim',
			
		];
	
	}
}
?<