2

我在这里提到了Laravel 4.2 Validation Rules - Current Password Must Match DB Value

这是我的密码确认规则:

 public static $ruleschangepwd = array(
    'OldPassword' =>  array( 'required'),  // need to have my rule here
    'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10'
    );

但我在模型中有我的规则

正如我在问题中看到的以下给定的自定义规则

Validator::extend('hashmatch', function($attribute, $value, $parameters)
{
    return Hash::check($value, Auth::user()->$parameters[0]);
});
$messages = array(
    'hashmatch' => 'Your current password must match your account password.'
);
$rules = array(
    'current_password' => 'required|hashmatch:password',
    'password'         => 'required|confirmed|min:4|different:current_password'
);

有可能有这样的规则吗?

 'OldPassword' =>  array( 'required', 'match:Auth::user()->password') 

像这样或比上面给出的任何简单的自定义规则?

注意:当我在模型中执行此操作时,我无法在我的模型中实现上述自定义规则。(或者如果我可以,我怎么能在模型中做到这一点)

更新 :

我可以用这样的东西吗

'OldPassword' =>  array( 'required' , 'same|Auth::user()->password'),

但我应该

Hash::check('plain text password', 'bcrypt hash')
4

1 回答 1

0

您必须使用自定义规则扩展验证器。但是,如果您在模型中拥有规则,那应该没问题。您可以在任何地方扩展验证器,并且该规则将在全球范围内可用。

我建议您在项目中添加一个新文件app/validators.php

然后在底部添加这一行app/start/global.php

require app_path().'/validators.php';

现在在里面validators.php定义验证规则

Validator::extend('match_auth_user_password', function($attribute, $value, $parameters){
    return Hash::check($value, Auth::user()->password);
}

(我将名称更改为更具描述性。您显然可以使用任何您喜欢的名称)

然后添加match_auth_user_password到您的规则中:

public static $ruleschangepwd = array(
    'OldPassword' =>  'required|match_auth_user_password',
    'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10'
);
于 2014-12-30T11:43:12.553 回答