Monday, December 17, 2012

Modificating validation rules in the CakePHP Models

There are many cases in which you need to add, modify or remove some validation rules that has already been set in the model. I was looking around how to do it and I found a good way to do it using the beforeValidate() callback form the model.

In my case I needed to save mora than one type of user, in one of them I didn't need to save the email address, but in the other case I did need it. This was the validation rule:

 'email' => array(  
  'rule'  => array('email', true),  
  'message' => 'Please supply a valid email address.'  

So what I did was to set this in the model:

 public function beforeValidate($options = array()) {  
  if (($this->data['User']['group_id'] == STUDENT) && empty($this->data['User']['email'])){  

With this I got to tell what type of user was being saved and if it was a "STUDENT" type of user and the email field was empty the rule for email was removed.

I hope you can use this.

No comments:

Post a Comment