how to validate form data in codeigniter 4



PHP Snippet 1:

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

PHP Snippet 2:

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

PHP Snippet 3:

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