Laravel use Hash as Validator

半城伤御伤魂 提交于 2019-12-07 17:31:44

问题


i'm using Hash::check() to check current password with entered password. i use this if for check this action

$HashPassowrd = Hash::make(Input::get('password'));

if( ! Hash::check( Input::get('currPassword') , $data->password ) )
{
   return Redirect::to('profile.update')
            ->withErrors('Current Password in Incorrect!');
}

how to use that as validator ? for example in this rules

$rules = array(
            'name'        => 'required|alpha',
            'family'      => 'required',
            'email'       => 'required|email',
            'currPassword'=> 'required',
            'password'    => 'required|confirmed',
            'password_confirmation'=>'required',
        );

回答1:


You can add custom rule in to the validator:

Validator::extend('checkHashedPass', function($attribute, $value, $parameters)
{
    if( ! Hash::check( $value , $parameters[0] ) )
    {
        return false;
    }
    return true;
});

Now you can use this custom rule as:

'currPassword' => 'required|checkHashedPass:' . Input::get('currPassword')

So, if the validation fails for this rule then you'll get error messages for this in your view and can access using $errors->first('currPassword'); but you need to pass a custom error message for this custom rule you've created using:

$messages = array( 'currPassword.checkHashedPass' => 'Current Password failed!' );

So, during validation you have to pass the $messages array using:

$validator = Validator::make(Input::all(), $rules, $messages);

Check custom validation rules on the documentation.




回答2:


You also can use a closure validation rule:


    [
        'currPassword' => function ($attribute, $value, $fail) {
            if (! Hash::check($value, $this->user()->password)) {
                $fail('Your current password doesnt match');
            }
        },
        'password' => 'required|min:6|confirmed',
    ];



来源:https://stackoverflow.com/questions/21802638/laravel-use-hash-as-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!