CakePHP custom validation with a variable in the error message

邮差的信 提交于 2019-12-19 07:11:41

问题


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.


回答1:


thats actually pretty easy. just return the error string!

return 'You have ' . ...;


来源:https://stackoverflow.com/questions/12014514/cakephp-custom-validation-with-a-variable-in-the-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!