How to validate time in laravel

2020-06-07 11:50发布

I want to validate time in Laravel. Ex:- I want that when user input the time between 8 PM to 10 PM then it will show the validation error. How can I achieve that in Laravel

7条回答
Root(大扎)
2楼-- · 2020-06-07 12:06

You probably should take a look to this bit of the documentations. A custom rule sounds like your way to go.

查看更多
小情绪 Triste *
3楼-- · 2020-06-07 12:07

Probably this code would work in your controller. However it won't validate times from different days (eg 9pm - 3am next day). time_start and time_end in this case should be provided as HH:mm but you can change it easily.

public function store(Illuminate\Http\Request $request)
{
    $this->validate($request, [
        'time_start' => 'date_format:H:i',
        'time_end' => 'date_format:H:i|after:time_start',
    ]);

    // do other stuff
}
查看更多
Animai°情兽
4楼-- · 2020-06-07 12:15

Create DateRequest and then add

<?php

namespace App\Http\Requests\Date;

use App\Http\Requests\FormRequest;


class DateRequest extends FormRequest
{
    /**
     * --------------------------------------------------
     * Determine if the user is authorized to make this request.
     * --------------------------------------------------
     * @return bool
     * --------------------------------------------------
     */
    public function authorize(): bool
    {
        return true;
    }


    /**
     * --------------------------------------------------
     * Get the validation rules that apply to the request.
     * --------------------------------------------------
     * @return array
     * --------------------------------------------------
     */
    public function rules(): array
    {
        return [

            'start_date' => 'nullable|date|date_format:H:i A',
            'end_date' => 'nullable|date|after_or_equal:start_date|date_format:H:i A'
        ];
    }
}
查看更多
混吃等死
5楼-- · 2020-06-07 12:15

Try This code

use Validator;
use Carbon\Carbon;


$timeHours = "7:00 PM";//change it to 8:00 PM,9:00 PM,10:00 PM  it works
$time = Carbon::parse($timeHours)->format('H');


$request['time'] = $time;
$validator = Validator::make($request->all(), [
    'time' => ['required','integer','between:20,22']
]);


 if ($validator->fails()) {
    dd($validator->errors());
}

enter image description here

查看更多
Explosion°爆炸
6楼-- · 2020-06-07 12:19
$beginHour = Carbon::parse($request['hour_begin']);
        $endHour = Carbon::parse($request['hour_end']);
        if($beginHour->addMinute()->gt($endHour)){
            return response()->json([
                'message' => 'end hour should be after than begin hour',
            ], 400);
        }

查看更多
地球回转人心会变
7楼-- · 2020-06-07 12:22

Use date_format rule validation

date_format:H:i

From docs

date_format:format

The field under validation must match the format defined according to the date_parse_from_format PHP function.

查看更多
登录 后发表回答