CakePHP custom validation with a variable in the error message
Asked Answered
C

1

6

Good afternoon.

I have a Model that has a field called "percentage". All similar Models cannot have their percentages add up to more than 100%. Checking for this is handled during validation.

I need the validation error message to say how much percentage "room" the user has left. For example, if all MyModels already have a total of 80% and the user tries to create a new MyModel with a percentage of 40%, the error message would say, "Your percentage is too high. You only have 20% remaining."

The problem is that I don't know how to put a variable in a validation error message.

In MyModel.php:

public $validate = array(
    'percentage' => array(
        'rule' => array('confirmValidPercentage', 'percentage'),
        'message' => 'foo',
        'required' => true,
    ),
);

public function confirmValidPercentage($data) {
    $percentage = floatval($data['percentage']);

    $total = 0.00;
    $weights = $this->find('all', array('recursive'=>-1));
    foreach ($weights as $weight) {
        $total += floatval($weight[$this->name]['percentage']);
    }

    if ($total + $percentage > 100) {
        // handle the error variable here
        return false;
    }
    else {
        return true;
    }
}

I have tried :

$this->validate['percentage']['message'] = 'You have '.(100-$total).'% remaining';

but the message element set here does not override the original message - the error message remains 'foo'. I tried removing the message element form the $validation array altogether, but it defaults to the parent name, i.e. 'percentage'. I tried:

unset($this->validate['percentage']['message']);

before setting the validate message but the result is the same.

Does anyone know how to return a variable in a validation error message? Thanks a lot.

Counterstamp answered 17/8, 2012 at 23:48 Comment(0)
K
9

thats actually pretty easy. just return the error string!

return 'You have ' . ...;
Kalevala answered 18/8, 2012 at 0:8 Comment(2)
Perfect! I thought a custom validation method could only return a boolean. Thanks.Counterstamp
I thought so too until very recently ;)Kalevala

© 2022 - 2024 — McMap. All rights reserved.