Reputation: 5456
I have created a custom validator class named "EndTimeValidator" in common\components namespace.
Code:
namespace common\components;
use yii\validators\Validator;
class EndTimeValidator extends Validator
{
public function init()
{
parent::init();
$this->message = 'Event EndTime must be greater than StartTime.';
}
public function validateAttribute($model, $attribute)
{
$startDate = $model->StartDate;
$endDate = $model->EndDate;
$startTime = $model->StartTime;
$endTime = $model->EndTime;
if( ($startDate == $endDate) && $startTime != "" && $endTime != "" )
{
if( strtotime($endTime) < strtotime($startTime) )
{
$this->addError($attribute, $this->message);
}
}
}
public function clientValidateAttribute($model, $attribute, $view)
{
$startDate = $model->StartDate;
$endDate = $model->EndDate;
$startTime = $model->StartTime;
$endTime = $model->EndTime;
if( ($startDate == $endDate) && $startTime != "" && $endTime != "" )
{
if( strtotime($endTime) < strtotime($startTime) )
{
return <<<JS
messages.push($this->message);
JS;
}
}
}
}
And in model I first included that path and defined the validation as below:
use common\components\EndTimeValidator;
['EndTime', EndTimeValidator::class],
Question updated:
But it is giving me below exception:
Call to a member function getAttributeLabel() on a non-object
I have referred to this link. Am I doing anything wrong? Please guide me. Thanks!
Upvotes: 0
Views: 61
Reputation: 5456
It was a silly mistake. But I will keep this question as it may help someone.
The error was due to the following line in the validateAttribute function
$this->addError($attribute, $this->message);
Replace the above line with:
$model->addError($attribute, $this->message);
Upvotes: 0
Reputation: 5032
Use:
use common\components\EndTimeValidator;
/** .... */
['EndTime', EndTimeValidator::class],
Upvotes: 1