问题
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