Laravel date_format 验证失败 HTML 输入类型周
Laravel date_format validation failing for HTML input type week
我从请求中得到了这些数据:
{
"type": "custom",
"start_week": "2020-W19"
}
我的验证规则是:
return [
'type' => 'required|in:standard,custom',
'start_week' => 'required|date_format:Y-\WW',
];
这给了我这个结果:
"errors": {
"start_week": [
"The start week does not match the format Y-\WW."
]
}
我之前使用这种格式来验证周类型输入,例如“2020-W19”。
我是不是做错了什么,我该怎么办?
我试过了。你的权利。令人惊讶的是它不起作用。
但这里有一种方法可以处理它。通过直接使用闭包和Carbon
实例,我们可以拥有自己的自定义规则,效果很好:
$request->validate([
'start_week' => [
'required',
function ($attribute, $value, $fail) {
if (!Carbon\Carbon::hasFormat($value, 'Y-\WW')) {
$fail('The '.$attribute.' is invalid.');
}
},
]
]);
更多信息:Doc
我从请求中得到了这些数据:
{
"type": "custom",
"start_week": "2020-W19"
}
我的验证规则是:
return [
'type' => 'required|in:standard,custom',
'start_week' => 'required|date_format:Y-\WW',
];
这给了我这个结果:
"errors": {
"start_week": [
"The start week does not match the format Y-\WW."
]
}
我之前使用这种格式来验证周类型输入,例如“2020-W19”。
我是不是做错了什么,我该怎么办?
我试过了。你的权利。令人惊讶的是它不起作用。
但这里有一种方法可以处理它。通过直接使用闭包和Carbon
实例,我们可以拥有自己的自定义规则,效果很好:
$request->validate([
'start_week' => [
'required',
function ($attribute, $value, $fail) {
if (!Carbon\Carbon::hasFormat($value, 'Y-\WW')) {
$fail('The '.$attribute.' is invalid.');
}
},
]
]);
更多信息:Doc