如何在 Laravel 5 中验证当前、新密码和新密码确认?

新手上路,请多包涵

我在 UserController@getProfilePasswordUserController@postProfilePassword 中创建了密码路由、视图和方法

目前,如果我填写了 new_password 字段,它会被正确地散列并提交到数据库,然后我可以使用新密码登录。

但我需要能够验证 new_passwordnew_password_confirm 以确保它们相同并验证用户的当前密码。

我怎样才能做到这一点?

编辑:我在方法中添加了 $this->validate ,但现在我不断收到错误 The password confirmation confirmation does not match. 即使它们匹配,因为我使用的是简单密码。另外我认为我需要手动检查当前密码,因为 validator 不会为我做。

 public function getProfilePassword(Request $request) {
    return view('profile/password', ['user' => Auth::user()]);
}

public function postProfilePassword(Request $request) {
    $user = Auth::user();

    $this->validate($request, [
        'old_password'          => 'required',
        'password'              => 'required|min:4',
        'password_confirmation' => 'required|confirmed'
    ]);

    $user->password = Hash::make(Input::get('new_password'));
    $user->save();
}

这就是观点

<form action="{{ route('profile/updatepassword') }}" method="post" enctype="multipart/form-data">
    <div class="form-group">
          <label for="name">Current Password</label>
          <input type="password" name="old_password" class="form-control" id="old_password">
    </div>
    <div class="form-group">
          <label for="name">Password</label>
          <input type="password" name="password" class="form-control" id="password">
    </div>
    <div class="form-group">
          <label for="name">New Password</label>
          <input type="password" name="password_confirmation" class="form-control" id="password_confirmation">
    </div>
    <button type="submit" class="btn btn-primary">Change Password</button>
    <input type="hidden" value="{{ Session::token() }}" name="_token">
 </form>

原文由 Halnex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

有一个 Hash::check() 功能可以让您检查用户输入的旧密码是否正确。

usage

 if (Hash::check("param1", "param2")) {
 //add logic here
}

param1 - user password that has been entered on the form
param2 - old password hash stored in database

如果已正确输入旧密码,它将返回 true,您可以相应地添加逻辑

对于 new_passwordnew_confirm_password 相同,您可以在表单请求中添加验证,例如

'new_password' => 'required',
'new_confirm_password' => 'required|same:new_password'

原文由 Sid 发布,翻译遵循 CC BY-SA 3.0 许可协议

laravel 8.* 的验证规则

默认

'current_password' => 'required|current_password',
'password' => 'required|min:8|confirmed',

风俗

php artisan make:rule MatchOldPassword

//inside MatchOldPassword
public function passes($attribute, $value)
{
   return Hash::check($value, auth()->user()->password);
}

 'current_password' => ['required', new MatchOldPassword()],
'password' => 'required|min:8|confirmed',

原文由 bhavinjr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题