Simple Validation Rule inside the Model

那年仲夏 提交于 2019-12-24 03:13:00

问题


I refered here Laravel 4.2 Validation Rules - Current Password Must Match DB Value

Here is my Rule for Password Confirmation :

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

But I am having my rules in the Model

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

Is it possible to have rule like this ?

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

Like this or Any simple custom rule than above given ?

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)

Update :

Can i use something like this

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

But i should

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

回答1:


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.

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

Then add this line at the bottom of app/start/global.php

require app_path().'/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)

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


来源:https://stackoverflow.com/questions/27700021/simple-validation-rule-inside-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!