Laravel:条件验证规则

时间:2020-02-17 16:43:47

标签: laravel validation conditional-statements rules

在我的laravel应用程序中,我需要基于条件基础应用验证规则。例如:在Store方法中,password字段是必填字段,并且最小字符:6。但是,在Update方法中,password字段不是必需字段,如果用户输入密码,则密码必须大于6个字符。

SomeController.php

private function validations($customRules = [])
{
    # variables
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'required|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];
    $messages = [
        'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
        'contact_person.min'      => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',

        'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
        'mobile_number.numeric'  => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',

        'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
        'email.email'    => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',

        'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
        'pword.min'      => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',

        'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
    ];

    if(!empty($customRules))
        $rules = \array_merge($rules, $customRules);

    # returning
    return request()->validate($rules, $messages);
}

修改规则后,根据update方法要求,对pword字段的最小字符进行验证。由于该字段为空,因此不应发生这种情况。

当前,我被迫这样做。

public function update()
{
    ...

    # validating submitted data
    if(!empty(request()->pword))
        $this->validations([ 'pword' => 'min:6' ]);
    else
        $this->validations([ 'pword' => '' ]);

    ....
}

1 个答案:

答案 0 :(得分:1)

您可以使用nullabe代替required,如果您使用的是雄辩的话,则空白值会转换为null,因为中间件低于

    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

所以您的方法就像

private function validations($request,$update = false){
    $rules = [
        'contact_person' => 'required|min:2',
        'mobile_number'  => 'required|numeric',
        'pword'          => 'nullable|min:6',
        'email'          => 'required|email',
        'address'        => 'required',
        'status'         => 'required',
    ];

}