Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp: how to set multiple validation in model for different actions?

I have a user model. In it, I have set validations that are used while registering user. That works fine. But when user edits his profile information, I don't want to validate some fields like password, email, etc. How it is possible. Below is code.

<?php
class User extends AppModel{

    var $name = 'User';

    // used when user registers
    var $validate = array(

        'login' => array(
            'minLength' => array(
                'rule' => array('minLength', '6'),
                'field' => 'login', 
                'message' => 'mimimum 6 characters long'
                )
        ),
        'password' => array( // don't want to validate in edit profile page
            'minLength' => array(
                'rule' => array('minLength', '6'),
                'field' => 'password',
                'message' => 'minimum 6 characters long'
                )
        ),
        'email' => array(
            array(
            'rule' => 'email',
            'message' => 'please enter a valid email address'
            )
        )
    );
?>

Above is used when I register a user. But when user edits his profile, I don't allow to edit/change user password. So each time while editing profile, it checks for password validation. I haven't added password field in edit profile page, I don't want to validate password field. So can I have different validation rules for different actions?

Thanks.

like image 970
gautamlakum Avatar asked Feb 25 '23 22:02

gautamlakum


1 Answers

Several ways to do this:

  • Use the on parameter to apply rules only to create or update actions.
  • unset the undesired rules from the model before validation.

    unset($this->User->validate['password']);
    
  • Use custom validation methods that are intelligent enough to figure out whether they should apply or not, e.g. by checking whether $this->id or $data['id'] is set or not. Not recommended unless you're sure what you're doing.

  • Use the $fieldlist parameter of the save method to limit saving and validation to specified fields only. Fields not in the list will neither be saved nor validated. Very recommended, since it also protects against form spoofing.

    $this->User->save($this->data, true, array('only', 'certain', 'fields'));
    
like image 100
deceze Avatar answered Apr 19 '23 22:04

deceze