模型内部的简单验证规则 [英] Simple Validation Rule inside the Model

查看:184
本文介绍了模型内部的简单验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里引用了 Laravel 4.2验证规则-当前密码必须与数据库值匹配

这是我的密码确认规则:

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

但是我在模型中有规则

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

As i saw the below given custom rule in the question

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') 

喜欢此规则还是任何简单的自定义规则?

注意::由于我在模型中执行此操作,因此无法在我的模型中实现上述自定义规则. (或者,如果可以的话,我该如何在模型中执行此操作)

Note : As i am doing this in model i can't implement the above custom rule in my model. (or If i can, How can i do that inside the model)

我可以使用这样的东西

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

但是我应该

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

推荐答案

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

You will have to extend the validator with a custom rule. However it should be no problem if you have your rules inside the model. You can extend the validator anywhere and the rule will be globally available.

我建议您将新文件添加到项目app/validators.php

I recommend you add a new file to your project app/validators.php

然后在app/start/global.php

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

现在在validators.php内部定义验证规则

Now inside validators.php define the validation rule

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

(我更改了名称以使其更具描述性.您显然可以使用喜欢的任何名称)

(I changed the name a bit to be more descriptive. You obviously can use whatever name you like)

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

And after that add match_auth_user_password to your rules:

public static $ruleschangepwd = array(
    'OldPassword' =>  'required|match_auth_user_password',
    'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10'
);

这篇关于模型内部的简单验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆