CakePHP 自定义验证与错误消息中的变量
下午好.
我有一个模型,它有一个名为百分比"的字段.所有类似模型的百分比总和不能超过 100%.验证过程中会对此进行检查.
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.
我需要验证错误消息来说明用户剩余的空间"百分比.例如,如果所有 MyModel 已经有 80% 的总数,而用户尝试创建一个百分比为 40% 的新 MyModel,则错误消息会显示您的百分比太高.您只剩下 20% 了".
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.
在 MyModel.php 中:
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;
}
}
我试过了:
$this->validate['percentage']['message'] = 'You have '.(100-$total).'% remaining';
但是这里设置的消息元素不会覆盖原始消息——错误消息仍然是foo".我尝试从 $validation 数组中完全删除消息元素,但它默认为父名称,即百分比".我试过了:
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.
推荐答案
那其实很简单.只返回错误字符串!
thats actually pretty easy. just return the error string!
return 'You have ' . ...;
相关文章