仅当存在其他字段时进行yii验证

仅当存在其他字段时进行yii验证,yii,Yii,我的表单中有两个字段,分别是开始日期和结束日期。仅当存在开始日期时,我才想验证结束日期 在rails中,我们有:if。我们在yii中是否有类似的功能?定义自定义函数以进行验证 定义规则: array('end_date','checkEndDate'); 定义自定义函数: public function checkEndDate($attributes,$params) { if($this->start_date){ if(!$this->validate_end_

我的表单中有两个字段,分别是
开始日期
结束日期
。仅当存在
开始日期时,我才想验证
结束日期


在rails中,我们有
:if
。我们在
yii
中是否有类似的功能?

定义自定义函数以进行验证

定义规则:

array('end_date','checkEndDate');
定义自定义函数:

public function checkEndDate($attributes,$params)
{
  if($this->start_date){
     if(!$this->validate_end_date($this->end_date))
         $this->addError('end_date','Error Message');
  }  
}
您可以使用
validate()
单独验证属性,因此您可以首先验证
start\u date
,如果有错误,则跳过验证,例如:

<?php
// ... code ...
// in your controller's actionCreate for the particular model

// ... other code ...

if(isset($_POST['SomeModel'])){
    $model->attributes=$_POST['SomeModel'];
    if ($model->validate(array('start_date'))){
    // alright no errors with start_date, so continue validating others, and saving record

         if ($model->validate(array('end_date'))){
         // assuming you have only two fields in the form, 
         // if not obviously you need to validate all the other fields,
         // so just pass rest of the attribute list to validate() instead of only end_date

              if($model->save(false)) // as validation is already done, no need to validate again while saving
                  $this->redirect(array('view','id'=>$model->id));
         }
    }
}
// ... rest of code ...
// incase you didn't know error information is stored in the model instance when we call validate, so when you render, the error info will be passed to the view
希望这有帮助。

免责声明:我不确定skipOnError解决方案,它可能会受到验证器顺序的影响,您可以测试它(我还没有测试),并了解它是否有效。当然,单个验证解决方案在任何一天都会起作用。

对于懒惰的人,在验证之前将条件验证添加到模型的
方法中:

if($this->start_date){
  if(!$this->validate_end_date($this->end_date))
    $this->addError('end_date','Error Message');
}  

一个字段基于另一个字段的验证可以在模型规则方法中完成。 这里是规则方法

        ['start_date','required','when'=>function($model) {
            return $model->end_date != '';
        }]

我希望这会对您有所帮助。

如果您需要任何澄清,请告诉我。我刚刚与Yii完成了此类验证。你可以从这里查阅。在Yii2中,您可以使用该属性。注意:上述解决方案适用于Yii2,您也应该注意,或者禁止将元素
'enableClientValidation'=>false
添加到上述数组中
        ['start_date','required','when'=>function($model) {
            return $model->end_date != '';
        }]