Laravel:条件验证规则

问题描述 投票:0回答:1

在我的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' => '' ]);

    ....
}
laravel validation conditional-statements rules
1个回答
0
投票

首先从pword中删除rules,然后再将$request->password传递给validations方法,否则,$request会更好,以便将来进行更多的条件检查

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

    ....
    ....
   if(!$update){
        $rules['pword'] = 'required|min:6';
    }else if($update && $request->password){
        $rules['pword'] = 'min:6';
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.