CodeIgniter Forums
Validation doesn't work - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Validation doesn't work (/showthread.php?tid=90274)



Validation doesn't work - Tokioshy - 02-27-2024

Like in the thread subject, I have an issue where if the first field is empty and then I click the submit button, it should show "is-invalid" class from bootstrap. But, I don't know why but in my case, "is-invalid" doesn't appear. To reconstruct it is in the video below, and the code is in the link provided. I'm using CodeIgniter v4.4.5

Code:
Comic.php: https://srcb.in/WpK36Jtntv
create.php: https://srcb.in/2bQAvdBdeG
BaseController.php: https://srcb.in/SzAbQ0mhtm
Routes.php: https://srcb.in/7xD5kTzVqt

Video tutorial + what I expected to be: https://youtu.be/IfMWgZf-To0?t=773

Video:
[Video: https://youtu.be/CshKImwRrcI]


RE: Validation doesn't work - kenjis - 02-27-2024

When the field is empty (invalid), you redirect to "/comic/create".
That is the browser send another request to the server.
So the $validation in the view is not the same instance as the Validation instance in the first request.

You saved the Validation instance into the flash message in the session.
You need to get it from the session.

See https://codeigniter4.github.io/CodeIgniter4/libraries/validation.html#redirect-and-validation-errors


RE: Validation doesn't work - MZahov - 02-27-2024

If your validation fail and you want to return view with errors it will be better to use 


PHP Code:
// Controller:            
if (!$this->validate([
   'judul' => 'required|is_unique[comic.judul]',
])) {
   return view('comic/create', [
       'errors' => $this->validator->getErrors(),
   ]);
}

// View:

isset($errors['judul']) ? 'is-invalid' ''



RE: Validation doesn't work - Tokioshy - 02-28-2024

(02-27-2024, 09:25 PM)kenjis Wrote: When the field is empty (invalid), you redirect to "/comic/create".
That is the browser send another request to the server.
So the $validation in the view is not the same instance as the Validation instance in the first request.

You saved the Validation instance into the flash message in the session.
You need to get it from the session.

See https://codeigniter4.github.io/CodeIgniter4/libraries/validation.html#redirect-and-validation-errors

Thank you! This one is work for me as well, I don't know if it's the good or the perfect one but at least, I've tried to find the code by myself and proud of myself because I can figure it out.  Cool

PHP Code:
<?= session()->getFlashdata('validation') ? 'is-invalid' '';  ?>