Custom Validation Rules in CakePHP 1.2
CakePHP’s validation class is pretty powerful, however there may be a time when you require a validation method that hasn’t been defined, this is where custom validation rules fit in.
Lets imagine you have a select box containing a users ‘title’ field in a form. You also have a ‘other_title’ text field which must be filled in if the ‘Other’ value is selected.
How would you go about validating this?
Simple: In your Model specify your validation criteria as so…
var $validate = array(
'title' => array(
'rule' => array('minLength',1),
'message' => 'Please select your title'
),
'other_title' => array(
'rule' => array('_compareFields', 'title', 'other'),
'message' => 'Please enter your other title'
)
);
As you can see when the Model validates, the ‘other_title’ field is validated against a custom rule named ‘_compareFields’ parsing in ‘title’ and ‘other’ as parameters.
‘title’ is the field to compare ‘title_other’ with and ‘other’ is the compare value that I am matching on.
Therefore the custom rule looks like:
function _compareFields($field=array(), $compare_field, $compare_value){
if(!empty($this->data[$this->name][$compare_field])&&(strtolower($this->data[$this->name][$compare_field]) == strtolower($compare_value))) {
$field_value = array_shift($field);
if(!empty($field_value)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
I could of simply used ‘Other’ as the $compare_value but I like writing generic functions that can be re-used multiple times. This function will now cater for other fields with different $compare_fields and the ‘case’ of this value is not sensitive in the view.
Hope that helps someone out there!
Tags: CakePHP, Custom, Validation

March 15th, 2009 at 10:27 pm
[...] CakePHP, I did some lovely custom validation to check if a guarantee code was valid (from a list of codes in a MySQL table) and also to see if [...]