How to define validation on fly in cakephp

Cakephp

Posted on 06 Jan 16 by Vickey
  1376



As we know that in cakephp we define our all form validation in our Model.

class User extends AppModel {
    public $validate = array(
		
		'cellnumber' => array(

			'isUnique' => array(
				'rule' => 'isUnique',
				'message' => 'cellnumber Already exist.'
			),
			'required' => array(
				'rule' => 'notEmpty',
				'message' => 'cellnumber is required.'
		)),

		'email' => array(

			'isUnique' => array(
				'rule' => 'isUnique',
				'message' => 'Email Already exist.'
			),
			'required' => array(
				'rule' => 'notEmpty',
				'message' => 'Email is required.'
		)),
		
        'name' => array(
            'required' => array(
				'rule' => 'notEmpty',
				'message' => 'Name is required'
             )
        ),
	);
}

But in some cases we do not need these validation on all form. For example if we have two different registration form for different types of users and for first type of user cellnumber is not required and for second type of user cellnumber is required then if I have define validation for cellnumber in Model then it will be mandatory for both type of users.So we can define this validation on fly also, where it need

public function saveUserTypeFirst(){

	if ($this->request->is('post')){
		$this->User->save();
	}
	
}
public function saveUserTypeSecond(){

	if ($this->request->is('post')){

		$this->User->validator()->add('cellnumber', 'required', array(
	        'rule' => array('notEmpty'),
	        'message' => 'cellnumber is required'
	    ))->add('cellnumber', 'isUnique', array(
	        'rule' => array('notEmpty'),
	        'message' => 'This cellnumber is already registered'));
	    $this->User->save();
    }
}

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com