Analyze. Act. Achieve.
Kurinchilion KURINCHILION Analyze. Act. Achieve.

News

CakePHP: Multi-validatable Behavior

Consider the following scenario where we have a database table:users and that we need carry the validations for the following forms i) Login ii) Change password iii) Add/Edit user records iv) Forgot password

You can either write separate controllers and have each controller call a model based on table: users to validate each input field or use the same user model to carry out different validations which sounds logical.

It is easy to carry out different validations in a cakephp model by using the Multi-validatable Behavior by having different validation sets for different testing conditions.

Key things to note here ...

i) Download the code for Multivalidatable Behavior and have it placed under /models/behaviors/ folder

ii) In the model where you want to have multi validation, you need to include multivalidatable behavior like var $actsAs = array("Multivalidatable");

iii) Add validation rulesets array like var $validationSets = array('login' => array('name'=>array('rule'=>'alphanumeric')), 'changepassword' => array('password'=>array('rule'=>'notEmpty')) );

iv) In the controller where you want to apply the validation rule set, you need to add the respective validation like

function login(){ $this->User->setValidation('login'); }

function changepassword(){ $this->User->setValidation('changepassword'); }

For more info visit CakePHP Bakery