Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a timestamp value in laravel 5

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

like image 263
MaGnetas Avatar asked May 18 '15 11:05

MaGnetas


2 Answers

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

like image 62
MURATSPLAT Avatar answered Oct 11 '22 01:10

MURATSPLAT


Use this rule

   public function rules()
    {
        return [
            'date_time' => 'date_format:Y-m-d H:i:s'
        ];
    }
like image 42
PHP Worm... Avatar answered Oct 10 '22 23:10

PHP Worm...