下午好.
我有一个模型,它有一个名为百分比"的字段.所有类似模型的百分比总和不能超过 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 ' . ...;
这篇关于CakePHP 自定义验证与错误消息中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
不能使用 'Object 作为类名,因为它是保留的Cannot use #39;Object as class name as it is reserved Cake 2.2.x(不能使用 Object 作为类名,因为它是保留的 Cake 2.2.x)
OAuth 重定向后会话丢失Session is lost after an OAuth redirect(OAuth 重定向后会话丢失)
Cakephp 3.x 中的分页排序Pagination Sort in Cakephp 3.x(Cakephp 3.x 中的分页排序)
CakePHP 多个应用程序的共享核心CakePHP Shared core for multiple apps(CakePHP 多个应用程序的共享核心)
在 CakePHP 3 上登录 [ Auth->identify() ] 始终为 falLogin [ Auth-gt;identify() ] always false on CakePHP 3(在 CakePHP 3 上登录 [ Auth-identify() ] 始终为 false)
致命错误:允许的内存大小为 134217728 字节已用尽Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 87 bytes)(致命错误:允许的内存大小为 134217728 字节已用尽