laravel中的输入验证?

时间:2014-03-31 11:00:23

标签: php laravel laravel-4

我有一个输入验证来更改用户密码,当我尝试提交表单时,我总是出现错误,即新密码和确认密码不匹配,这是我的帖子:

public function doChangePassword()
{
    if(Auth::check())
    {
    $validator = Validator::make(Input::all(), User::$updatePasswordRules);

    // if the validator fails, redirect back to the form
    if ($validator->fails()) {
        return Redirect::to('change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
    } else {
        // store
        $user = User::find(Auth::user()->id);
        if(Auth::user()->password==Input::get('new_password')){
        $user->password = Hash::make(Input::get('new_password'));
        $user->save();
        }
        else{
            return Redirect::to('change-password')->with('message', 'The password is not correct');
        }

        // redirect
        Session::flash('message', 'Successfully updated password!');
        return Redirect::to('login');
    }
    }
    else{
        return Redirect::to('login');
    }
}

这是我的规则:

 public static $updatePasswordRules = array(
    'password'=>'required|alpha_num|between:6,12',
    'new_password'=>'required|alpha_num|between:6,12|confirmed',
    'password_confirmation'=>'required|alpha_num|between:6,12'
);

所以如果有人有想法我会非常感激

1 个答案:

答案 0 :(得分:1)

这是因为Laravel希望(针对您的具体情况)confirmed字段命名为new_password_confirmation

来自doc"验证字段必须具有foo_confirmation的匹配字段。例如,如果验证字段是password,则输入中必须存在匹配的password_confirmation字段。"

因此规则应该看起来像(也改变表单中的输入名称):

 public static $updatePasswordRules = array(
    'password'=>'required|alpha_num|between:6,12',
    'new_password'=>'required|alpha_num|between:6,12|confirmed',
    'new_password_confirmation'=>'required|alpha_num|between:6,12'
);

或者您可以使用same验证规则(如果您不想更新表单输入):

 public static $updatePasswordRules = array(
    'password'=>'required|alpha_num|between:6,12',
    'new_password'=>'required|alpha_num|between:6,12|same:password_confirmation',
    'password_confirmation'=>'required|alpha_num|between:6,12'
);