繁体   English   中英

如何有条件地验证 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为 false,则time_starttime_end字段是必需的。 这似乎按预期工作。

但是,如果我提交一个closed为 true 的请求,我就会陷入我的自定义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 ,然后在rulepasses方法中,您可以执行以下操作:

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

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM