Yii2日期比较验证

时间:2015-08-31 09:41:17

标签: validation date yii2 compare-attribute

我有下面的模型规则(),但它不起作用。它始终显示错误消息。

public function rules()
{
    return [
        [['start_date','end_date'], 'date', 'format' => 'php:F d Y'],
        ['start_date','compare','compareAttribute'=>'end_date','operator'=>'<'],
        ['end_date','compare','compareAttribute'=>'start_date','operator'=>'>'],
    ];
}

2 个答案:

答案 0 :(得分:12)

public function rules()
{
    return [
        [['start_date','end_date'], 'date', 'format' => 'php:F d Y'],
        ['start_date','validateDates'],
    ];
}


public function validateDates(){
    if(strtotime($this->end_date) <= strtotime($this->start_date)){
        $this->addError('start_date','Please give correct Start and End dates');
        $this->addError('end_date','Please give correct Start and End dates');
    }
}

您应该编写客户端验证。 http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation

答案 1 :(得分:2)

您可以为此问题使用默认的比较验证

['fromDate', 'date', 'timestampAttribute' => 'fromDate'],
['toDate', 'date','timestampAttribute' => 'toDate'],
['fromDate', 'compare', 'compareAttribute'=> 'toDate', 'operator' => '<', 
'enableClientValidation' =>false],

Yii compare validation