Set::merge() and dynamic validation rules

Here’s another trick with Set::merge()…

Let’s say we’ve defined some basic validation rules in our Profile model, something like:

var $validate = array (
   'name' => array(
      'rule' => array('notEmpty'),
      'required' => false,
      'message' => 'Please enter a name'
     )

  .... and so on for all other fields ...

);

Now we’ve got an action where this particular set of rules isn’t going to fly…

Maybe the data is coming from an external (somewhat untrusted) source and in this case we need to make sure that the ‘name’ is present in the data array (i.e. ‘required’=>true) and that it’s not only ‘notEmpty’, but now it has to be ‘alphaNumeric’.

So we do an easy “update” to our default rules, which we’ve previously defined in the model:

$this->Profile->validate = Set::merge($this->Profile->validate, array(
      'name'=>array(
         'required'=>true,
         'rule'=>array('alphaNumeric')
      )
));

What happened is that now all our default rules remain as we have defined them in the model, but the ‘name’ field is now going to be validated using this new set of rules.

The theory is that you set your $validate array with some default rules that will apply in most of the situations, and use this technique when your validation rules have to change for a few fields in any given action.

To make things even cleaner you should probably add a method to AppModel called something like modifyValidate, and then you could use:

$this->Profile->modifyValidate(… array of new rules…);

%d bloggers like this: