我想验证Laravel的时间。例如: - 我希望当用户输入晚上8点到晚上10点之间的时间时,它会显示验证错误。我怎样才能在Laravel中实现这一目标
答案 0 :(得分:22)
这个代码可能适用于您的控制器。然而,它不会在不同日期(例如,第二天晚上9点至次日凌晨3点)验证时间。在这种情况下,time_start
和time_end
应该以{{1}}的形式提供,但您可以轻松更改。
HH:mm
答案 1 :(得分:10)
使用date_format规则验证
date_format:H:i
来自docs
date_format:format
验证字段必须与根据date_parse_from_format PHP函数定义的格式匹配。
答案 2 :(得分:2)
尝试此代码
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());
}
答案 3 :(得分:2)
创建DateRequest,然后添加
<?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'
];
}
}
答案 4 :(得分:0)
您可能应该查看this位文档。自定义规则听起来像是你要走的路。
答案 5 :(得分:0)
在Lavavel 5.6中:
位于/ app / Http / Requests / YourRequestValidation中的文件中
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class YourRequestValidation extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'initial_time' => 'required',
'end_time' => 'required',
'end_time' => 'after:initial_time'
];
}
/**
* Custom message for validation
*
* @return array
*/
public function messages()
{
return [
'initial_time.required' => 'Please, fill in the initial time',
'end_time.required' => 'Please, fill in the end time.',
'end_time.after' => 'The end time must be greater than initial time.'
];
}
}
答案 6 :(得分:0)
$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);
}