Welcome

Welcome to the personal website of Sussex based web developer Karl Rixon.

Latest Article:

Alternative Error Messages From CakePHP Custom Validation Methods

Sometimes when validating a model in CakePHP, you need to use a custom validation method:

1
2
3
4
5
6
7
8
9
10
public $validate = array(
    'fieldName' => array(
        'rule' => 'customMethod',
        'message' => 'Default error message'
    ),
);

public function customMethod($check) {
    return $check == 'correct!';
}

This works well, but what if you want your custom method to check for various states and respond with a custom error message? This is very simple to do, but it is not documented in the Book. All you need to do is, instead of returning a boolean from your custom method, simply return the error message as a string. Strings of length > 0 are treated by Cake as errors automatically. That’s it!

1
2
3
4
5
6
7
8
9
public function customMethod($check) {
    if ($check == 'foo') {
        return 'You cannot use foo!';
    } else if ($check == 'bar') {
        return 'bar is not allowed!';
    } else {
        return true;
    }
}