Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: How to validate datetime input from 4 input fields?

I have a form which includes a deadline and the user should set the deadline in four input fields like this:

<div class="form-group col-lg-3">
    {!! Form::label('year', 'Year', ['class' => 'control-label']) !!}
    {!! Form::selectYear('year',$year, $year +1, null , ['class' => 'form-control']) !!}
</div>
<div class="form-group col-lg-3">
    {!! Form::label('month', 'Month', ['class' => 'control-label']) !!}
    {!! Form::selectRange('month', 1, 12 , null , ['class' => 'form-control']) !!}
</div>
<div class=" form-group col-lg-3">
    {!! Form::label('day', 'Day', ['class' => 'control-label']) !!}
    {!! Form::selectRange('day', 1, 31 , null , ['class' => 'form-control']) !!}
</div>
<div class=" form-group col-lg-3">
    {!! Form::label('hour', 'Hour', ['class' => 'control-label']) !!}
    {!! Form::selectRange('hour', 6, 23 , null , ['class' => 'form-control']) !!}
</div>

In a formRequest, I'm compiling these four fields into a deadline. So my formRequest is like this:

public function rules()
    {
        $this->prepInput();
        return [

        ];
    }
    public function prepInput(){
        $input=$this->all();
        ...
        $input['deadline']=$this->prepDeadline($input['hour'], $input['month'], $input['day'], $input['year']);
        ...
        $this->replace($input);
    }


    public function prepDeadline($hour,$month,$day, $year){

            $time = jDateTime::mktime($hour, 0, 0, $month, $day, $year);
            return $deadline = strftime("%Y-%m-%d %H:%M:%S", $time);        
    }

The deadline is a Jalali datetime and I need to check if the user have selected a valid date or not (e.g. 1394/12/31 is not a valid date). The jDatetime package has a checkdate method which works exactly like php checkdate. Where and how can I validate the date in this formRequest and notify the user to select a valid date? In fact I need this validation to take place before the deadline is passed to prepInput.

like image 901
Ali Erfani Avatar asked Jul 27 '15 07:07

Ali Erfani


1 Answers

Laravel's Validator has a date_format rule, so when setting the rules in the form request, you should be able to simply add something like:

public function rules()
{
    $this->prepInput();
    return [
        'deadline' => 'date_format:Y-m-d H:i:s'
    ];
}

Then in your view:

@if ($errors->has('deadline'))
    {{ $errors->first('deadline') }}
@endif

You could also simplify your prepInput method by simply concatenating the year/month/day/hours into a string to create the deadline; it'll be essentially the same thing.

like image 115
benJ Avatar answered Oct 04 '22 15:10

benJ