如何在codeigniter 4中验证表单数据

1cklez4t  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(147)

我是新的codeigniter 4,我目前正在建立一个注册表。当我提交注册表,它给予所需字段的错误,即使我填写所有字段的正确数据。
下面是我代码片段

function register() {
        $data = [];
        helper(['form']);
        if($this->request->getMethod() == "post"){
            $validation =  \Config\Services::validation();

            $validation->setRules([
                "firstname" => ["label" => "First Name", "rules" => "required|min_length[3]|max_length[20]"],
                "lastname" => ["label" => "Last Name", "rules" => "required|min_length[3]|max_length[20]"],
                "email" => ["label" => "Email", "rules" => "required|min_length[3]|max_length[20]|valid_email|is_unique[users.email]"],
                "password" => ["label" => "Password", "rules" => "required|min_length[8]|max_length[20]"],
                "password_confirm" => ["label" => "Confirm Password", "rules" => "matches[password]"],
            ]);

            if($validation->run()){
                
                $user = new UserModel();
                $userdata = [
                    "firstname" => $this->request->getVar("firstname"),
                    "lastname" => $this->request->getVar("lastname"),
                    "email" => $this->request->getVar("email"),
                    "password_confirm" => $this->request->getVar("password_confirm"),
                ];
                $user->save($userdata);
                $session = session();
                $session->setFlashData("success", "Successful Registration");
                return redirect()->to('/');

            }else{
                $data["validation"] = $validation->getErrors();
            }

        }

        echo view('templates/header', $data);
        echo view('register');
        echo view('templates/footer');
    }

这是我要验证的登记表。

<form class="" action="/register" method="post">
          <div class="row">
            <div class="col-12 col-sm-6">
              <div class="form-group">
               <label for="firstname">First Name</label>
               <input type="text" class="form-control" name="firstname" id="firstname" value="<?= set_value('firstname') ?>">
               <small class="text-danger"><?= isset($validation) ? $validation['firstname'] : null;  ?></small>
              </div>
            </div>
            <div class="col-12 col-sm-6">
              <div class="form-group">
               <label for="lastname">Last Name</label>
               <input type="text" class="form-control" name="lastname" id="lastname" value="<?= set_value('lastname'); ?>">
               <small class="text-danger"><?= isset($validation) ? $validation['lastname'] : null ;  ?></small>
              </div>
            </div>
            <div class="col-12">
              <div class="form-group">
               <label for="email">Email address</label>
               <input type="text" class="form-control" name="email" id="email" value="<?= set_value('email') ?>">
               <small class="text-danger"><?= isset($validation) ? $validation['email'] : null ;  ?></small>
              </div>
            </div>
            <div class="col-12 col-sm-6">
              <div class="form-group">
               <label for="password">Password</label>
               <input type="password" class="form-control" name="password" id="password" value="">
               <small class="text-danger"><?= isset($validation) ?  $validation['password'] :null ; ?></small>
             </div>
           </div>
           <div class="col-12 col-sm-6">
             <div class="form-group">
              <label for="password_confirm">Confirm Password</label>
              <input type="password" class="form-control" name="password_confirm" id="password_confirm" value="">
              <small class="text-danger"><?= isset($validation) ?  $validation['password_confirm'] :null ; ?></small>
            </div>
          </div>
          </div>

          <div class="row">
            <div class="col-12 col-sm-4">
              <button type="submit" class="btn btn-primary">Register</button>
            </div>
            <div class="col-12 col-sm-8 text-right">
              <a href="/">Already have an account</a>
            </div>
          </div>
        </form>

and here is the output i am getting even if i fill all fields.

wlp8pajw

wlp8pajw1#

试试这个样式

function register()
{
    $data = [];
    helper(['form']);
    if ($this->request->getMethod() == "post") {
        $validation =  \Config\Services::validation();

        $rules = [
            "firstname" => [
                "label" => "First Name", 
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "lastname" => [
                "label" => "Last Name", 
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "email" => [
                "label" => "Email", 
                "rules" => "required|min_length[3]|max_length[20]|valid_email|is_unique[users.email]"
            ],
            "password" => [
                "label" => "Password", 
                "rules" => "required|min_length[8]|max_length[20]"
            ],
            "password_confirm" => [
                "label" => "Confirm Password", 
                "rules" => "matches[password]"
            ]
        ];

        if ($this->validate($rules)) {

            $user = new UserModel();
            $userdata = [
                "firstname" => $this->request->getVar("firstname"),
                "lastname" => $this->request->getVar("lastname"),
                "email" => $this->request->getVar("email"),
                "password_confirm" => $this->request->getVar("password_confirm"),
            ];
            $user->save($userdata);
            $session = session();
            $session->setFlashData("success", "Successful Registration");
            return redirect()->to('/');
        } else {
            $data["validation"] = $validation->getErrors();
        }
    }

    echo view('templates/header', $data);
    echo view('register');
    echo view('templates/footer');
}

只需将规则放入数组中并将其传递给控制器验证函数。
我希望能成功

qlzsbp2j

qlzsbp2j2#

如果您希望始终验证进入该模型的数据,则可能需要考虑在模型内部进行验证:
https://codeigniter.com/user_guide/models/model.html#validating-data
如果你想在模型之外验证数据,你必须告诉验证服务数据在哪里,因为它可以是POST、GET,甚至只是你从其他地方得到的数组。
在您的情况下,您需要验证数据与您的请求。
https://codeigniter.com/user_guide/libraries/validation.html?highlight=validation#withrequest
因此,您的验证代码应该类似于:

if($validation->withRequest($this->request)->run()){ }

这将在GET和POST中查找数据。
如果要指定并且只使用POST

if($validation->withRequest($this->request->getPost())->run()){ }

相关问题