【问题标题】:Validation issue in laravel update functionlaravel 更新功能中的验证问题
【发布时间】:2020-07-29 17:57:52
【问题描述】:

我的 laravel 应用程序中有一个管理仪表板

从仪表板管理员可以编辑用户配置文件内容。

这是我当前的用户控制器(仅包括更新功能)

public function update(Request $request, $id)
{
    $this->validate($request, [
        'name' => ['required', 'alpha','min:2', 'max:255'],
        'last_name' => ['required', 'alpha','min:2', 'max:255'],
        'email' => ['required','email', 'max:255', 'unique:users,email,'.$id],
        'password' => ['same:confirm-password','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
        'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{9})$/','numeric','min:9'],
        'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users,username,'.$id],   
        'roles'=>['required'],
        //'user_roles'=>['required'],
    ]);

    $input = $request->all();
    if(!empty($input['password'])){ 
        $input['password'] = Hash::make($input['password']);
    }else{
        $input = array_except($input,array('password'));    
    }

    $user = User::find($id);
    $user->update($input);
    DB::table('model_has_roles')->where('model_id',$id)->delete();

    $user->assignRole($request->input('roles'));

    if($input['roles']=='customer'){
        return redirect()->route('customers.index')
                    ->with('success','Customer has been updated successfully');
    }
    else{
        return redirect()->route('users.index')
                    ->with('success','User has been updated successfully');
    }
}

现在我的问题是,

当管理员在不更改密码字段的情况下更新用户时,密码字段会得到验证,并向我抛出与密码相关的正则表达式错误...

如何避免该问题并仅在更改密码字段时验证密码字段。

【问题讨论】:

  • @DigitalDrifter 我已经使用相同的验证密码字段:确认密码,所以我需要再次验证确认密码字段吗?
  • 但是在默认的 laravel auth 使用注册中,只有密码字段被验证对吗?
  • 将nullable 添加到password 规则是否有效?即:'password' => 'nullable|same:...'。如果管理员不填写,password 字段应该为空,而nullable 作为第一条规则,应该阻止检查其他规则。

标签: php laravel validation laravel-5 laravel-6


【解决方案1】:

根据您当前的验证规则,密码字段将始终使用正则表达式进行检查。在密码验证规则的首位添加nullable 规则可以帮助您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2020-02-26
    • 2020-11-11
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多