6

I have model rules() like below, but it is not working. It is showing error message always.

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'=>'>'],
    ];
}
shreenu konapala
  • 379
  • 1
  • 3
  • 7

2 Answers2

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

you should write Client-Side Validation. http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation

shreenu konapala
  • 379
  • 1
  • 3
  • 7
  • 5
    There is another way to do it: https://github.com/yiisoft/yii2/commit/1621f65545d24b03f80477aee286cf4be8e6faa4 – cebe Jun 20 '16 at 13:04
9

You can use default compare validation for this issue

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

Yii compare validation

ABIRAMAN
  • 929
  • 8
  • 12
  • Nice solution, but need to remember about "format". – TomaszKane May 31 '19 at 13:53
  • Also, if you use a consistent, reverse date format for each, such as 'format' => 'php:Y-m-d', then you don't need to specify timestampAttribute. If you do specify timestampAttribute, the default behaviour is to display the error but replace the date values that were input with their timestampAttributes, which is not very user-friendly. – Rich Harding Dec 17 '20 at 14:46