Reputation: 2991
I want to allow multiple formats for a field in Yii2
ActiveRecord
like:
public function rules()
{
return [
['date', 'date', 'format' => 'php:Y-m-d H:i'],
['date', 'date', 'format' => 'php:Y-m-d'],
];
}
But like this it fails if any of them fails. I there any way to do it rules
?
Currently I'm thinking of doing it in beforeValidate
like:
public function beforeValidate()
{
$this->date = date('Y-m-d H:i', strtotime($this->date));
return parent::beforeValidate();
}
What is the best way to do it?
Upvotes: 1
Views: 246
Reputation: 2332
Looks like you want to match multiple date and time formats? Try this way:
['date', 'match', 'pattern' => '#^(?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)( ([01][0-9]|2[0-3]):([0-5][0-9]))?$#']
Upvotes: 0
Reputation: 151
You can create Custom Rule it work like this .
Just add under rule
['date','datefunction']
public function datefunction($attribute,$params){
$date = $this->$attribute;
/*****check validation******/
$this->addError($attribute, "Date : $date Format is wrong");
}
Note: Your may get DB exception error. You need to change format once saving a file.
Upvotes: 1
Reputation: 583
You can do it by making function, for example validateDateFormat()
and to handle logic inside it, and then in rules you say ['date', 'validateDateFormat']
, refer to Yii's documentation for more informations.
Upvotes: 1