Laravel 5.3使用自定义验证 [英] Laravel 5.3 use custom validation
本文介绍了Laravel 5.3使用自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Laravel 5.3.我想使用表单验证来测试用户密码的哈希值.
I use Laravel 5.3. I want to use form validation to test the hash for user's password.
这是我的代码:
$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 ?
解决方案:
好的,以简单的方式完成此操作的最佳方法是,将扩展名放在make之前:
Ok, the best way to do it in simple way, 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',
]);
推荐答案
您的自定义规则old_password可以这样使用
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',
]);
扩展验证器. CheckPassword是带有isValid()方法的类.
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将类似于
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.
}
这篇关于Laravel 5.3使用自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文