yii2 - 我想在规则中做一个比较值,当一个值必须大于一个值并且小于另一个值时
问题描述
我想比较一个需要大于 8 或小于 3 的值,但我似乎无法正确判断。到目前为止,如果值小于 8,我可以让它显示错误消息。我的规则是
['taskmonth', 'compare', 'compareValue' => 8, 'operator' => '>', 'when'=> function($model){
return $model->repeating_type == self::SIXMONTHLY;
}, 'whenClient' => "function(attribute, value) {
return $('#repeating_type').val() = self::SIXMONTHLY;
}", 'message' => 'The start month can only be September, October, November, December, January or February'],
这是我模型中的规则。I get the correct error message when any month apart from Sept, Oct, Nov or Dec is selected but it should allow you to select Jan or Feb as well. 我尝试使用 < 3 的 2 条规则,但无论我当时尝试选择哪个月份,都会收到一条错误消息。我在文档中找不到任何东西来显示有两个比较值。我可以这样做吗?
解决方案
您的情况有几种解决方案。
1)如果为此使用比较规则至关重要,则只有当此值在您的限制范围内时,您才能激活它。
[
'taskmonth', 'compare', 'compareValue' => 3, 'operator' => '>',
'when'=> function($model){ return $model->taskmonth >= 3 && $model->taskmonth <= 8 && $model->repeating_type == self::SIXMONTHLY; },
'whenClient' => "function(attribute, value) { return value >= 3 && value <= 8 && $('#repeating_type').val() == '". self::SIXMONTHLY. "'; }",
'message' => 'The start month can only be September, October, November, December, January or February'
],
[
'taskmonth', 'compare', 'compareValue' => 8, 'operator' => '<',
'when'=> function($model){ return $model->taskmonth >= 3 && $model->taskmonth <= 8 && $model->repeating_type == self::SIXMONTHLY; },
'whenClient' => "function(attribute, value) { return value >= 3 && value <= 8 && $('#repeating_type').val() == '". self::SIXMONTHLY. "'; }",
'message' => 'The start month can only be September, October, November, December, January or February'
]
2)你可以从另一端工作。当你有 self::SIXMONTHLY 时,运行“in”规则。如果您确定在项目范围内有可用的:
[
'taskmonth', 'in','range'=>[1,2,9,10,11,12],
'when'=> function($model){ return $model->repeating_type == self::SIXMONTHLY; },
'whenClient' => "function(attribute, value) { return $('#repeating_type').val() == '". self::SIXMONTHLY. "'; }",
'message' => 'The start month can only be September, October, November, December, January or February'
]
3)同样在这种情况下,您可以使用匹配规则而不是:
'taskmonth', 'match','pattern'=> '/^[^3-8]/', 'when' => ...
PS还有一个小提示:return $('#repeating_type').val() = self::SIXMONTHLY;
这不是比较。这是申请。我想你的意思是==
推荐阅读
- linux - 如何将 reaver 降级为 reaver 1.4 [Makefile:13:wash] 错误 1?
- php - INPUT 适用于 MAMP,但不适用于网络服务器
- python-3.x - 如何增加范围内的第一个数字?
- angular - 谷歌分析被导航器阻止
- python - 在文本文件中查找多个正斜杠
- angular - Angular 9 - chartjs-plugin-annotation 错误
- python - Python:控制台上的输出带有Parantheses
- sql - 将行透视到列 Oracle SQL
- python - AttributeError:'super'对象在python中没有属性'__getattr__'
- tkinter - 在 Tkinter 文件对话框中关闭历史列表框