我正在研究Laravel表单字段,并添加了2个日期输入字段(出发日期和返回日期)。我正在尝试在Laravel中创建一个自定义后端验证,其中出发日期必须在现在之后,而返回日期必须在出发日期之后6天。请协助?
验证参数
'departure_date' => 'required|date|after:now',
//Must be 6 days after departure date
'return_date' => 'required|date|after:departure_date + 6 day',
我正在使用的验证逻辑
//Added at the top of the controller
use Illuminate\Foundation\Http\FormRequest;
//Controller code
public
function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'departure_date' => 'required|date|after:now',
//Must be 6 days after departure date
'return_date' => ['required', 'date', function ($attribute, $value, $fail) {
if (strtotime($value) < strtotime(request('departure_date')) + 518400) {
$fail('Departure date invalid');
}
}
]
]
}
答案 0 :(得分:0)
使用此
SRC_PATH specifies a directory
DEST_PATH does not exist
DEST_PATH is created as a directory and the contents of the source directory are copied into this directory
并设置此规则
$date = Carbon\Carbon::parse($date_from);
$sixdays = $date->addDays(6);
答案 1 :(得分:0)
您可以使用Closure
解决方案。
$validator = \Validator::make($request->all(), [
'departure_date' => 'required|date|after:now',
//Must be 6 days after departure date
'return_date' => ['required', 'date', function ($attribute, $value, $fail) {
if (strtotime($value) < strtotime(request('departure_date')) + 518400 /* 6*24*60*60 */) {
$fail('Departure date invalid');
}
}
],
]
);
编辑
您不需要在顶部添加FormRequest
,并且您的代码中缺少密码。
function validatePlanEntries(Request $request)
{
$validator = \Validator::make($request, [
'departure_date' => 'required|date|after:now',
//Must be 6 days after departure date
'return_date' => ['required', 'date', function ($attribute, $value, $fail) {
if (strtotime($value) < strtotime(request('departure_date')) + 518400) {
$fail('Departure date invalid');
}
}]
]);
if ($validator->fails()) {
//return errors in $validation->error();
}
//else continue
}