Tuesday, July 3, 2012

All about validation in Yii - PART1

Validation in YII (Server side & Client Side)- PART 1

Yii support server side validation & client side validation and it has wide range of built in validators, here we are going to see the each and every points about validation features that Yii provide.

Declaring Validation Rules

We specify the validation rules in Model class through the rules() method which should return an array of rule configurations. validators are called in order if we specified more than one validator for attribute
rules() method is a default method that triggers yii validation by using rules() method while validate() called. validate() function triggered automatically while we call $model->save() orcall $model->validate().

Validation rule syntax

array('AttributeList', 'Validator', 'on'=>'ScenarioList'...),

Here AttributeList defines the list of model attributes, if more than one attribute it should be separated by comma.
Validator defines type of validation to be done yii provides the built in validators for email, url and so on refer table 1 for built in validators.
ScenarioList tells on which scenario the validation rule should fire, more than one scenario will be separated by comma.

Adding validations to model

public function rules(){
return array('username','required');
}

the above validation rule tells the yii to validate username fields to be mandatory through required validator. we apply same validation rule for more than one field, by separating them with comma

Above example tells yii to validate username attribute length should have 3-12 and it is required.

Yii triggers validation when we call $model->validate(); or $model->save(); While saving records validation automatically called by default, if validation should be avoided in save methods $model->save(false); //which cancels validation