Forms 选择字段的Yii2验证规则
例如,我有一个模型。有一块田。此字段包含选定选项的数组。是否可以为此字段编写规则以检查选择了多少项?我需要写一个条件,用户必须检查至少2个选项,最多5个 我尝试过类似的方法,但不起作用(如果至少选择了一个选项,则可以提交表单)Forms 选择字段的Yii2验证规则,forms,yii2,yii2-validation,Forms,Yii2,Yii2 Validation,例如,我有一个模型。有一块田。此字段包含选定选项的数组。是否可以为此字段编写规则以检查选择了多少项?我需要写一个条件,用户必须检查至少2个选项,最多5个 我尝试过类似的方法,但不起作用(如果至少选择了一个选项,则可以提交表单) 公共功能规则() { 返回[ [“成分”],“必需”], [‘成分’、‘检查排列’] ]; } 公共函数checkIsArray($attribute,$params) { if(空($this->components)){ $this->addError($attrib
公共功能规则()
{
返回[
[“成分”],“必需”],
[‘成分’、‘检查排列’]
];
}
公共函数checkIsArray($attribute,$params)
{
if(空($this->components)){
$this->addError($attribute,“config不能为空”);
}
elseif(计数($this->components)>5){
$this->addError($attribute,“选择更多”);
}
elseif(count($params)addError($attribute,“选择较少”);
}
}
可以,但在最后一个条件elseif(count($params)components
数组中,变量赋值错误,即$params
。并且您不需要进行第一次检查,将属性添加到所需规则中就足以检查提交时它是否为空
将验证函数更改为
public function checkIsArray( $attribute , $params ) {
if ( count ( $this->ingredients ) > 5 ) {
$this->addError ( $attribute , "Choose No more than 5" );
} elseif ( count ( $this->ingredients ) < 2 ) {
$this->addError ( $attribute , "Choose No less than 2" );
}
}
公共函数checkIsArray($attribute,$params){
如果(计数($this->components)>5){
$this->addError($attribute,“选择不超过5”);
}elseif(计数($this->components)<2){
$this->addError($attribute,“选择不少于2”);
}
}
在发布之前,我刚刚用
kartik\Select2
multiselect测试了它,它工作得很好,但是如果它仍然有相同的反应,你需要添加控制器/动作
代码,希望它能帮助你。只是一个问题,你使用的是高级应用程序
还是基本
?
public function checkIsArray( $attribute , $params ) {
if ( count ( $this->ingredients ) > 5 ) {
$this->addError ( $attribute , "Choose No more than 5" );
} elseif ( count ( $this->ingredients ) < 2 ) {
$this->addError ( $attribute , "Choose No less than 2" );
}
}