2
votes

In Yii I am writing a small application called Invoice Application. In that I have two fields called Invoice Issue Date and Due Date. I want validation for both of the input date fields so that Due Date must be greater than Invoice Issue Date. So I made the following rule in the model:

public function rules (){
    array('due_date','compare','compareAttribute'=>'invoice_issue_date',
          'operator'=>'>',
          'allowEmpty'=>false,'message'=>'Due Date must be greater then Invoice Issue Date.'),
}

It is working fine but when in one field there is a two digit date (10 to 31) and another has a single digit date (1 to 9) then this validation not working at all. Can someone tell me what is wrong here? Any help and suggestions are welcome.

UPDATE

For dates I am using CJuiDatePicker to enter date fields.

1
Which field would have the single digit date and which the two digit date in order for this not to work? - Sammaye
Also what do you mean by one digit and two digit? Is that the real values of the date fields or is it just shorthand for a date format? - Sammaye

1 Answers

0
votes

I think, this is a common mistake many PHP developers do.

if( '2012-07-23' > '2012-08-17' ) 
// this is equivalent to comparing two strings , not dates

correct way is ...

if( strtotime('2012-07-23') > strtotime('2012-08-17') ) 
// I prefer to use "mktime" than "strtotime" for performance reasons

you may want to write your own validation method or convert those dates to integers before validation.

EDIT

add this to your model class

public function rules () {
    array('due_date', 'isDueDateGreater'),
}

public function isDueDateGreater($attribute, $params) {
    if( strtotime($this->due_date) < strtotime($this->invoice_issue_date) ) 
        $this->addError('due_date', 'Due Date must be greater then Invoice Issue Date.');
}