Yii条件验证


Yii Conditional Validation

我有一个关于Yii验证的问题。我有一个下拉框,它的选项是Y和n。如果用户选择Y,用户必须解释为什么他选择Y,因此一个textArea框将成为必需的。

我的规则代码如下所示:

array('explain', 'check', 'trigger'=>'med_effects'),

Check是我用来验证的函数

public function check($attribute, $params)
    {
        if($this->$params['trigger'] == 0 && $this->$attribute == '') {
            $this->addError($attribute, 'Explain the effects of the medicine');
        }
    }

"$this->$params['trigger']"保持不变。我假设因为保存的值是0(Y),即使用户选择n也不会改变,我应该如何确定用户在提交表单时选择了哪个选项?

谢谢。

在模型中创建一个属性:

public $isDropDownChecked;

在你的视图中,创建一个连接到新创建属性的下拉菜单。

并在方法rules()中返回一个规则数组,如下所示:

public function rules()
{
   $rules[] = array(); 
   if ($this->isDropDownChecked == 'Y')
        $rules[] = array('explain', 'check', 'trigger'=>'med_effects');    

   return $rules;
}

这也可能对Yii1上的人有所帮助,假设您有三个查找[Yes|NO]的字段,并且您希望至少有一个字段被选择为Yes

这是解决方案在模型上添加

public $arv_refill;
public $prep_refilled;
public $prep_initiate;

在你的规则中添加

public function rules()
{
    return array(
   array('arv_refill,prep_refilled,prep_initiate','arvPrepInitiateValidation'),
    );
 }

arvprepinitiatevalvalidation是一个函数

public function arvPrepInitiateValidation($attribute_name,$params)
    {
        
        if($this->arv_refill != 1 && $this->prep_refilled != 1 && $this->prep_initiate != 1){
            $msg = "arv_refill, prep_refilled or prep_initiate field must have one field as Yes";
            $this->addError('arv_refill',$msg);
            $this->addError('prep_refilled',$msg);
            $this->addError('prep_initiate',$msg);
        }
    }