4.1.5 Custom Validation Rules
If you haven’t found what you need thus far, you can always create your own validation rules. There are two ways you can do this: by defining custom regular expressions, or by creating custom validation methods.
4.1.5.1 Custom Regular Expression Validation
If the validation technique you need to use can be completed by using regular expression matching, you can define a custom expression as a field validation rule.
var $validate = array(
'login' => array(
'rule' => array('custom', '/^[a-z0-9]{3,}$/i'),
'message' => 'Only letters and integers, min 3 characters'
)
);
var $validate = array('login' => array('rule' => array('custom', '/^[a-z0-9]{3,}$/i'),'message' => 'Only letters and integers, min 3 characters'));
The example above checks if the login contains only letters and integers, with a minimum of three characters.
4.1.5.2 Custom Validation Methods
Sometimes checking data with regular expression patterns is not enough. For example, if you want to ensure that a promotional code can only be used 25 times, you need to add a custom validation function, as shown below:
<?php
class User extends AppModel {
var $name = 'User';
var $validate = array(
'promotion_code' => array(
'rule' => array('limitDuplicates', 25),
'message' => 'This code has been used too many times.'
)
);
function limitDuplicates($data, $limit){
$existing_promo_count = $this->find( 'count', array('conditions' => $data, 'recursive' => -1) );
return $existing_promo_count < $limit;
}
}
?>
<?phpclass User extends AppModel {var $name = 'User';var $validate = array('promotion_code' => array('rule' => array('limitDuplicates', 25),'message' => 'This code has been used too many times.'));function limitDuplicates($data, $limit){$existing_promo_count = $this->find( 'count', array('conditions' => $data, 'recursive' => -1) );return $existing_promo_count < $limit;}}?>
If you want to pass parameters to your custom validation function, add extra elements onto the ‘rule’ array, and handle them as extra params (after the main $data param) in your custom function.
Your custom validation function can be in the model (as in the example above), or in a behavior that the model implements. This includes mapped methods.
Note that the model/behavior methods are checked first, before looking for a method on the Validation class. This means that you can override existing validation methods (such as alphaNumeric()) at an application level (by adding the method to AppModel), or at model level.
