I'm writing validator rules for checking if the data is valid before adding a new Eloquent model record.
It's quite clear with strings, decimals and integers.
But what about a timestamp field?
I added the column using timestamp
method in one of my DB migrations, it works just fine. The only thing I need is to make sure the passed value will be a valid timestamp before executing the query.
Is there a direct/simple way or should I write a regexp for that?
Thank you
I think that validate like this..
$rules = ['start_at' => 'date_format:Y-m-d H:i:s'];
Let's test this rule
public function testSimpleTimeStampValidation()
{
$data = ['start_at' => '2015-12-1 12:12:58'];
$rules = ['start_at' => 'date_format:Y-m-d H:i:s'];
$validator = \Validator::make($data, $rules);
$this->assertTrue($validator->passes()); // passed !
}
Again trying test with unwanted date format..
public function testSimpleTimeStampValidation()
{
$data = ['start_at' => '12-1-2015 12:12:58'];
$rules = ['start_at' => 'date_format:Y-m-d H:i:s'];
$validator = \Validator::make($data, $rules);
$this->assertTrue($validator->passes()); // Failed !
}
It looks this rules works very well..
more details Data Format Validation in L5
Use this rule
public function rules()
{
return [
'date_time' => 'date_format:Y-m-d H:i:s'
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With