Reputation: 10714
I use Laravel 5.3. I want to use form validation to test the hash for user's password.
Here is my code :
$validator = Validator::make($request->all(), [
'old_password' => 'required|max:20|min:6',
'new_password' => 'required|max:20|min:6',
'new_password_confirm' => 'required|same:new_password',
]);
// test old password
if (! Hash::check($request->old_password, $user->user_passwd)) {
$validator->errors()->add('end', 'The end time must be within three hours of the start');
}
This is not working, even if the conditon is verified. I've tested this :
Validator::extend('old_password', function($attribute, $value) use ($user) {
return Hash::check($value, $user->user_passwd);
});
But I don't understand how to use this ?
Upvotes: 2
Views: 1415
Reputation: 10714
I found the solution. The best way to do it in simple way is to place the extend before the make :
Validator::extend('checkPassword', function ($attribute, $value, $parameters, $validator) use($user) {
return Hash::check($value, $user->user_passwd);
}, 'Your message error !');
$validator = Validator::make($request->all(), [
'old_password' => 'required|max:20|min:6|checkPassword',
'new_password' => 'required|max:20|min:6',
'new_password_confirm' => 'required|same:new_password',
]);
Upvotes: 1
Reputation: 2617
Your custom rule old_password can be used like this
$validator = Validator::make($request->all(), [
'old_password' => 'required|max:20|min:6|checkpassword',
'new_password' => 'required|max:20|min:6',
'new_password_confirm' => 'required|same:new_password',
]);
Extend validator. CheckPassword is class with method isValid().
Validator::extend('checkpassword', function ($attribute, $value, $parameters, $validator) {
return (new CheckPassword($attribute, $value, $parameters, $validator))->isValid();
});
CheckPassword.php will be like
/**
* Attribute being tested
*
* @var mixed
*/
protected $attribute;
/**
* Value of the attribute
*
* @var mixed
*/
protected $value;
/**
* Array of parameters passed to the value
*
* @var array
*/
protected $parameters;
/**
* Validator instance
*
* @var mixed
*/
protected $validator;
/**
* Class constructor
*
* @param mixed $attribute
* @param Uploaded $value
* @param array $parameters
* @param mixed $validator
*/
public function __construct($attribute, $value, $parameters, $validator)
{
$this->attribute = $attribute;
$this->value = $value;
$this->parameters = $parameters;
$this->validator = $validator;
}
public function isValid()
{
$value = $this->value; //Old password Value
//after this you can check hash and return true or false.
}
Upvotes: 3