Yii min date validation rule

2019-09-07 16:21发布

问题:

How can I add a minimum date validation rule in a Model?

Example:

I have a column dt_ini as DATE, which I need to restrict the input as D+7, on create.

If today is: october 1st, 2012

the minimum valid date on create would be: october 8th, 2012.

Otherwise, I would throw a validation error as: Your date must be at least 7 days from now.

The code I would expect is something like this: (this is NOT tested, and probably won't work)

    public function rules(){
      return array('dt_ini', 'date', 'minDate' => '+7'),
    }

Thanks.

回答1:

Is this what you are looking for?



回答2:

Create custom valid rule as follows:

class YourModel extends CActiveModel
{
    // some....

    public function rules(){
      return array('dt_ini', 'dateValid', 'minDate' => '+7 day', 'on' => 'create');
    }

    public function dateValid($attribute, $params)
    {
        $valid=null;
        $today = date('Y-m-d', time());
        if(isset($params['minDate']))
            $valid = date('Y-m-d', strtotime($params['minDate'])); //+7 day

        if( !is_null($valid) )
        {  //for increamental date
            if($this->dt_ini >  $valid || $this->dt_ini < $today )
                $this->addError($attribute, 'enter error message');     
        }
    }
}


标签: yii