Validations and print errors of forms in CodeIgniter 4 with Bootstrap 5 style

Validations are a fundamental mechanism that we use to show errors that occur in a form, therefore, in Codeigniter 4 we can quickly create validation rules from within the framework, in a configuration file of the same and configure it anywhere from our drivers.

We are going to see how we can use the validations on our form, for this we can basically do it in two ways, the first would be on the function that is in charge of receiving the data that we created previously, for example, the create function, to create a new element , in this case, a person:

    public function create(){
        $movie = new MovieModel();
        if($this->validate('movies')){
            $id = $movie->insert([
                'title' =>$this->request->getPost('title'),
                'description' =>$this->request->getPost('description'),
            ]);
            return redirect()->to("/movie/$id/edit")->with('message', 'Película creada con éxito.');
        }
        return redirect()->back()->withInput();
    }

Validation files

CodeIgniter from version 4 allows creating validation files, in which it would simply be an array, which we have to implement with the validations and we simply place the validations that we want to use; the file is located in app/Config/Validation and you simply have to define your validation rules:

    public $movies =[
        'title' => 'required|min_length[3]|max_length[255]',
        'description' => 'min_length[3]|max_length[5000]'
    ];

Basically very similar to the previous example, but in this way it is much more organized, more extensible and therefore more usable.

The point here is that you place as the key of the previous array the name of the field followed by the rules that you can see what types of rules you can place in the official documentation.

So now we have a schema that we can use to work with validations.

Show validation errors

We have to show the validation errors in the new view, for that we have to load a validation service from this file that we then pass to the view to show them:

  public function new()
    {
        $validation =  \Config\Services::validation();
        return view('person/new',['validation' => $validation]);
    }

And in the view we receive a collection, that is, a list of errors that we can print as follows:

<?= $validation->listErrors() ?>

To give a custom style for errors; You can go to the Config/Validation.php file and in the templates variable, indicate the reference to the file that must be used as a template to print the errors; for example:

    public $templates = [
        //'list'   => 'CodeIgniter\Validation\Views\list',
        'list'   => 'App\Views\Validations\list_bootstrap',
        'single' => 'CodeIgniter\Validation\Views\single',
    ];

Create template to display errors with Bootstrap

And we create such a file, for example, with the Bootstrap style:

<?php if (! empty($errors)) : ?>
    <div class="errors" role="alert">      
        <?php foreach ($errors as $error) : ?>
            <div class="alert alert-danger"><?= esc($error) ?></div>
        <?php endforeach ?>
    </div>
<?php endif ?>

But, as you can see, you can customize it 100% and include, for example, your style that you have for other CSS kits like Tailwind.css

Remember that this is part of me Course and book in CodeIgniter 4.

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.