CakePHP custom validation with a variable in the error message(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 ' . ...;
这篇关于CakePHP 自定义验证与错误消息中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CakePHP 自定义验证与错误消息中的变量
基础教程推荐
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01