验证在Codeigniter中返回空数组

7hiiyaii  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(124)

型号:

protected $validationRules = [
    'username' => 'required'
];
protected $validationMessages = [
    'username' => [
        'required' => 'Please enter a username'
    ]
];

控制器:

if($this->request->getMethod()== 'post'){
    
                $usermodel = new \App\Models\Users;
                $User = $usermodel
                ->where('username' , $this->request->getPost('username'))
                ->first();
    
                if(!$User){
                    print_r($usermodel->errors());
                    /*return redirect()->to('/login')->with('errors' , $usermodel->errors())->withInput();*/
                }

检视:

<?php if(session()->has('errors')): ?>
    <div class="alert alert-warning">
        <ul>
            <?php foreach(session('errors') as $error): ?>
                
                    <li><?= $error ?></li>
                
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

我知道我已经注解掉了return语句。我在控制器中得到了与print_r()相同的空数组,也得到了“return redirect with view”。

**但是:**如果我在控制器中手动指定闪存消息,则会收到“错误pw”消息:

if(!$UserFromDB){
                return redirect()->to('/login')->with('errors' , array('Wrong pw'))->withInput();
                /*print_r($usermodel->errors());*/
                /*return redirect()->to('/login')->with('errors' , $usermodel->errors())->withInput();*/
 }
pwuypxnk

pwuypxnk1#

我不认为我们在模型中使用表单验证,而是在控制器中使用表单验证。

#Controller     
if($this->request->getMethod()== 'post'){
$rules = ['username' => ['rules' => 'required];
$messages = ["username" => [
                "required" => "Please enter a username",
            ],
        ];
if($this->validate($rules,$messages)){
// validation succeed
}
else{
// validation not ok
            $response = [
                'message' => $this->validator->getErrors()
            ];
            
            $data['response'] = $response;
            //  redirect to your login view        
        }
}

相关问题