Search code examples
angularjslaravellaravel-5date-rangelaravel-validation

Laravel Validate Moment.js Date


I am trying to validate the date range in Laravel where the data is sent from my Angular Javascript.

Frontend Angular sends the date range using moment.js like this:

            var endDate = moment();
            var startDate = moment().subtract(29, 'days');

            var apiDateRange = {
                'startDate': startDate.format(),
                'endDate': endDate.format()
            };

In console, I can see that the date is posted like this:

endDate     2015-09-14T15:39:53+05:30
startDate   2015-08-16T15:39:53+05:30

I am trying to validate the date in Laravel. From reading the docs, I see that I need to use date_format for this. But I am getting the format wrong. This is what I have tried so far and are obviously wrong:

$validator = Validator::make($postData, [
   'startDate' => 'date_format:"Y-m-d H:i:s.u"|required'
   'endDate' => 'date_format:"Y-m-d H:i:s.u"|required'
]);


// AND

$validator = Validator::make($postData, [
   'startDate' => 'date_format:"Y-m-d\TH:i:s"|required',
   'endDate' => 'date_format:"Y-m-d\TH:i:s"|required',
]);

I read the php date doc and I am confused on putting together the date_format for this. Can someone kindly help me out here please?


Solution

  • Can't you pass as a date string like 2015-06-10 01:10:25 when formatting

    var format_to = 'YYYY-MM-DD HH:mm:ss';
    
    var apiDateRange = {
       'startDate': startDate.format(format_to),
       'endDate': endDate.format(format_to)
    };
    

    Plus i think its better to have validation like 'startDate' => 'required|date'