php Laravel 5.3使用自定义验证

bvuwiixz  于 2023-08-02  发布在  PHP
关注(0)|答案(2)|浏览(118)

我使用Laravel 5.3。我想使用表单验证来测试用户密码的哈希值。
下面是我的代码:

$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');
}

字符串
这是行不通的,即使条件得到验证。我测试了这个:

Validator::extend('old_password', function($attribute, $value) use ($user) {
    return Hash::check($value, $user->user_passwd);
});


但我不知道怎么用这个?

at0kjp5o

at0kjp5o1#

您的自定义规则old_password可如下使用

$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',
]);

字符串
扩展验证程序。CheckPassword是一个方法isValid()的类。

Validator::extend('checkpassword', function ($attribute, $value, $parameters, $validator) {
            return (new CheckPassword($attribute, $value, $parameters, $validator))->isValid();
        });


CheckPassword.php将像

/**
 * 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.
}

xxe27gdn

xxe27gdn2#

我找到解决办法了。最好的简单方法是将extend放在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',
]);

字符串

相关问题