CakePHP自定义验证与错误消息中的一个变量 [英] CakePHP custom validation with a variable in the error message
问题描述
下午好。
我有一个Model有一个名为percentage的字段。所有类似模型的百分比不能超过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.
我需要验证错误消息来说明用户剩余多少百分比房间。例如,如果所有MyModels已经有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数组一起删除消息元素,但它默认为父名称,即percent。我试过:
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 ' . ...;
这篇关于CakePHP自定义验证与错误消息中的一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!