Date validation


In working with date input, there is no mechanism to validate dates.
I want to know if it’s a valid format but also if it’s in a valid range.


On the client side, I’d strongly recommend using a date picker widget like DateTimePicker to enforce a specific format. As far as I can tell, jQuery Validate doesn’t have a built-in date range validator, but you can try implementing a custom rule as suggested here.

On the server side, you can use Carbon’s comparison methods to confirm that the dates are within a specific range. My typical approach for dealing with date inputs is as follows:

<input type="text" class="form-control js-date-picker" name="date" autocomplete="off" value="{{}}" placeholder="Date">
<input type="text" class="form-control js-time-picker" name="time" autocomplete="off" value="{{obj.time}}" placeholder="Time">

Then I install "eonasdan-bootstrap-datetimepicker" : "#latest" in my bower.json and include the "vendor/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css" and "vendor/eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker.js" assets in appropriate asset bundles.

In my page-specific JS I do:

        var form = modal.find('.js-form');

        // Initialize date and time pickers
            format: 'MM/DD/YYYY'

            format: 'LT'

For the server-side code:
Since I use the same expected date and time formats in every widget, I factored out the expected formats into a config setting:

        'site' => [
            'formats' => [
                'date' => 'm/d/Y',
                'time' => 'h:i+A'

Now in my controllers, I can transform the date and time inputs into a Carbon object:

$data['occurred_at'] = Carbon::createFromFormat($config[''] . ' ' . $config['site.formats.time'], $data['date'] . ' ' . $data['time']);

At this point, you could use the aforementioned comparison methods that Carbon offers, to do any range validation you need. The nice thing about Carbon is that Eloquent automatically recognizes and converts Carbon objects into the format expected for SQL’s timestamp type. So, all you have to do is assign the Carbon object to the model object’s property and everything else will be taken care of for you.