Pweb
Pweb

Reputation: 165

Laravel Custom Validation of Two Dates

I'm creating a form in Laravel which has two fields: departure-date and return-date. I'm trying to create custom validation logic where the departure date entered MUST be on the same day or any other date after the user fills in the form. The return-date should also be after the departure date. Kindly assist?

Form Layout

<!-- Departure date-->
<div class="form-line registar2 love {{ $errors->has('departure_date') ? ' has-error' : '' }}">
    <input type="date" class="form-input" name="departure_date" value="{{ old('departure_date') }}" required>
    <label>Departure Date *</label>
    <div class="error-label">Field is required!</div>
    <div class="check-label"></div>
    @if ($errors->has('departure_date'))
        <span class="help-block">
            <strong>{{ $errors->first('departure_date') }}</strong>
        </span>
    @endif
</div>
<!--End departure-->

<!-- Return date-->
<div class="form-line registar2 move {{ $errors->has('return_date') ? ' has-error' : '' }}">
    <input type="date" class="form-input" name="return_date" value="{{ old('return_date') }}" required>
    <label>Return Date *</label>
    <div class="error-label">Field is required!</div>
    <div class="check-label"></div>
    @if ($errors->has('return_date'))
        <span class="help-block">
            <strong>{{ $errors->first('return_date') }}</strong>
         </span>
    @endif
</div>
<!-- End return date-->

Validation in Controller

public function validatePlanEntries(Request $request)
{
    $validation = $this->validate($request, [
            'departure_date' => 'required',
            'return_date' => 'required'
        ]
    );
}

Upvotes: 1

Views: 5951

Answers (1)

Dimitri Mostrey
Dimitri Mostrey

Reputation: 2340

    public function validatePlanEntries(Request $request)
    {
        $validation = $this->validate($request, [
            'departure_date' => 'required|date|after:now',
            'return_date' => 'required|date|after:departure_date',
        ]
        );
    }

FYI: the after:xxxxx rule either compares to another input field or respects the rules of the native DateTime PHP class. So you may enter after:now +2 hours.

To override the messages and write your own, create a messages() function like this:

public function messages()
{
    return [
        'departure_date.required' => 'Departure date is required',
        'departure_date.after' => 'Please choose a date in the future',
        'return_date.required'  => 'Return date is required',
        'return_date.after' => 'Your return date is before departure'
    ];
}

Just in case you are looking for a jquery solution to make datepicking more user friendly and less error bound, you may have a look at Bootstrap Datepicker, it's probably worth the effort. Good luck on your project!

Upvotes: 5

Related Questions