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

时间:2012-03-03 04:29:09

标签: yii

我的表单中有两个名为start dateend date的字段。我想仅在end date出现时验证start date

在rails中,我们有:if。我们在yii中有类似的内容吗?

4 个答案:

答案 0 :(得分:13)

定义您的自定义功能以进行验证。

定义规则:

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');
  }  
}

答案 1 :(得分:2)

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

scroll

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

您可以使用validate() method来验证属性单独,这样您就可以先验证start_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

或者您也可以使用CValidator classskipOnError属性:

// in your model's rules, mark every validator rule that includes end_date as skipOnError,
// so that if there is any error with start_date, validation for end_date will be skipped
public function rules(){
     return array(
         array('start_date, end_date', 'required', 'skipOnError'=>true),
         array('start_date, end_date', 'date', 'skipOnError'=>true),
         // The following rule is used by search().
         // Please remove those attributes that should not be searched.
         array('id, start_date, end_date', 'safe', 'on'=>'search'),
     );
}

希望这有帮助。
免责声明:我不确定skipOnError解决方案,它可能会受到验证器顺序的影响,你可以测试它(我还没有测试过),并找出它是否有效。个人验证解决方案当然可以在任何一天使用。