2012-03-03 66 views
3

我在我的表單中有兩個字段名爲start dateend date。只有當start date存在時,我纔要驗證end dateyii驗證只有當另一個字段存在

在導軌中,我們有:if。我們有沒有類似於yii

+0

我剛剛用Yii完成了這種驗證。你可以從這裏引用它。 http://chevronscode.com/index.php/yii-model-rules-dynamic-required-if-extension.html – chen 2014-12-11 09:35:34

+0

在** Yii2 **中,您可以使用['when'](http:// www。 yiiframework.com/doc-2.0/guide-input-validation.html#conditional-validation)屬性。 – 2015-05-26 12:09:46

回答

11

定義您的自定義函數進行驗證。

定義規則:

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

另外,您也可以使用skipOnError屬性CValidator class

// 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解決方案,它可能受驗證程序順序的影響,您可以測試它(我還沒有測試過),並確定它是否有效。個人驗證解決方案當然會在任何一天工作。

+0

讓我知道你是否需要任何澄清。 – 2012-03-03 06:29:40

1

對於懶惰,條件驗證添加到模型中的beforeValidate方法:

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

驗證一個字段基於其他的可以在模型規則的方法來進行。 以下是規則方法。

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

我希望這會幫助你。

+1

注意:上述解決方案適用於Yii 2 – 2017-07-07 15:18:47

相關問題