【问题标题】:Simple Validation Rule inside the Model模型内的简单验证规则
【发布时间】:2015-02-26 07:08:35
【问题描述】:

我在这里提到了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')

【问题讨论】:

    标签: php laravel laravel-4 validationrules


    【解决方案1】:

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

    我建议你在项目中添加一个新文件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-06-26
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 2017-01-07
      相关资源
      最近更新 更多