I'm porting my application from CI3 to CI4.
Having issues with the form validation. My goal is to validate the input only if the form is submitted. In Codeigniter 3 a could do:
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run()) {
$username = $this->input->post('username');
...
} else {
...
}
And then it my view, I could display my errors:
echo validation_errors();
or display an error individually:
echo form_error('username');
All the errors would be displayed if the form was submitted. When I visit the page for the first time, no errors are shown.
Now in Codeigniter 4:
My controller is set up like this:
$validation = \Config\Services::validation();
$validation->setRule('username', 'Username', 'required|min_length[6]');
if ($validation->withRequest($this->request)->run()) {
$username = $this->request->getVar('username');
...
} else {
...
}
The validation is working, but the errors are displayed always. Even when the form is not submitted.
Make sure you are only validating upon a 'post' request.
You can utilize $this->request->getMethod()
inside a controller to check what type of request it is.
You can do something like this:
if($this->request->getMethod() == 'post')
{
// Validation
}