如何有条件地验证 Laravel 中的自定义规则?
How can I conditionally validate a custom rule in Laravel?
在我的控制器中,我有一个 store
方法来验证请求数据:
$request->validate([
'title' => 'required',
'description' => 'required',
'date' => [
'required',
new DateFormatRule
],
'closed' => 'nullable',
'time_start' => 'required_if:closed,0',
'time_end' => [
'required_if:closed,0',
new TimeDurationRule($request->time_start)
],
]);
closed
是一个布尔值。如果 closed
为假,则需要 time_start
和 time_end
字段。这似乎按预期工作。
但是,如果我提交一个 closed
为真的请求,我就会陷入我的习惯 TimeDurationRule
:
'time_end' => [
'required_if:closed,0',
new TimeDurationRule($request->time_start)
],
如何使 new TimeDurationRule($request->time_start)
成为条件?例如,如果 closed
为真,我手动将 time_end
设置为 null
,因此 time_start
/time_end
不需要值(不需要)。
如果我将自定义规则注释掉,一切都会按预期进行。
感谢您的任何建议!
您可以将 $request->closed
传递给您的 TimeDurationRule
,然后在 rule
的 passes
方法中,您可以这样做:
class TimeDurationRule implements Rule
{
public $closed;
public function __construct(/*all needed parameters*/, $closed)
{
$this->closed = $closed;
}
public function passes($attribute, $value)
{
if(!$closed){
return true
}
// the rest of validation logic
}
}
然后
new TimeDurationRule(/*all needed parameters*/, $request->closed)
您也可以在这里阅读更多相关信息:https://laracasts.com/discuss/channels/laravel/create-custom-validation-rule-with-additional-parameters-implement-in-request
希望对您有所帮助!
在我的控制器中,我有一个 store
方法来验证请求数据:
$request->validate([
'title' => 'required',
'description' => 'required',
'date' => [
'required',
new DateFormatRule
],
'closed' => 'nullable',
'time_start' => 'required_if:closed,0',
'time_end' => [
'required_if:closed,0',
new TimeDurationRule($request->time_start)
],
]);
closed
是一个布尔值。如果 closed
为假,则需要 time_start
和 time_end
字段。这似乎按预期工作。
但是,如果我提交一个 closed
为真的请求,我就会陷入我的习惯 TimeDurationRule
:
'time_end' => [
'required_if:closed,0',
new TimeDurationRule($request->time_start)
],
如何使 new TimeDurationRule($request->time_start)
成为条件?例如,如果 closed
为真,我手动将 time_end
设置为 null
,因此 time_start
/time_end
不需要值(不需要)。
如果我将自定义规则注释掉,一切都会按预期进行。
感谢您的任何建议!
您可以将 $request->closed
传递给您的 TimeDurationRule
,然后在 rule
的 passes
方法中,您可以这样做:
class TimeDurationRule implements Rule
{
public $closed;
public function __construct(/*all needed parameters*/, $closed)
{
$this->closed = $closed;
}
public function passes($attribute, $value)
{
if(!$closed){
return true
}
// the rest of validation logic
}
}
然后
new TimeDurationRule(/*all needed parameters*/, $request->closed)
您也可以在这里阅读更多相关信息:https://laracasts.com/discuss/channels/laravel/create-custom-validation-rule-with-additional-parameters-implement-in-request
希望对您有所帮助!