How to write custom template for validation error messages in Codeigniter4

Codeigniter4 has provision for custom templates to modify the display html for validation error messages.
Often we do not want to repeat the entire html on every page where the validation message is shown.

We can create a custom template and call the template reference when we are displaying the error message.

Let us look at an example. We will create a simple registration form and validate the fields and display error message with a custom html.

  1. Let us create a custom error html view file custom_error_view.php under App/Views folder.
<span class="alert-danger"><strong><?= esc($error) ?><strong></span>

2. We have to register this custom template in app/Config/Validation.php file. Find the variable public array $templates and add your custom template name followed by the path as below.

<?php

namespace Config;

class Validation extends BaseConfig
{
   
    /**
     * Specifies the views that are used to display the
     * errors.
     *
     * @var array<string, string>
     */
    public array $templates = [
        'list'   => 'CodeIgniter\Validation\Views\list',
        'single' => 'CodeIgniter\Validation\Views\single',
        'custom_error_view' => 'App\Views\custom_error_view',    //this is a custom template
    ];
}

3. Create a Controller Form.php under App/Controllers folder.

<?php 
namespace App\Controllers;

use CodeIgniter\Controller;
class Form extends Controller
{
    function __construct()
	{
        $this->validation = \Config\Services::validation();
        $this->input = \Config\Services::request();
	} 
    public function index(){
        $data = array();
        $data['validation'] = $this->validation; //Capture validation errors
        $data['input'] = $this->input->getPost();
        if($this->input->getPost('register')) {
             //set validation Rules
            $this->validation->setRule('username', 'User Name', 'required');
            $this->validation->setRule('email', 'Email', 'required|valid_email');
            $this->validation->setRule('password', 'Password', 'required');

            //Run validation rule
            if($this->validation->run($this->input->getPost()) ){
                echo "Validation successful";
                print_r($this->input->getPost());
                exit;
                //Proceed to process the record and redirect
            }
        }

        echo view("App\Views\client",$data);
    }
}

4. Create the registration form View client.php under App/Views folder.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="content">

<form class="form-horizontal" action='' method="POST">
  <fieldset>
    <div id="legend">
      <legend class="">Register</legend>
    </div>
    <div class="control-group">
      <label class="control-label"  for="username">Username</label>
      <div class="controls">
        <input type="text" id="username" name="username" value="<?=isset($input['username']) ? $input['username'] : ""?>" placeholder="" class="input-xlarge">
        <?php echo $validation->showError('username','custom_error_view');?>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label" for="email">E-mail</label>
      <div class="controls">
        <input type="text" id="email" name="email" value="<?=isset($input['email']) ? $input['email'] : ""?>" placeholder="" class="input-xlarge">
        <?php echo $validation->showError('email','custom_error_view');?>
      </div>
    </div>
 
    <div class="control-group">
      <label class="control-label" for="password">Password</label>
      <div class="controls">
        <input type="password" id="password" value="<?=isset($input['password']) ? $input['password'] : ""?>" name="password" placeholder="" class="input-xlarge">
        <?php echo $validation->showError('password','custom_error_view');?>
      </div>
    </div>
 
    <div class="control-group">
      <!-- Button -->
      <div class="controls">
        <button class="btn btn-success" value="register" name="register">Register</button>
      </div>
    </div>
  </fieldset>
</form>
</div>
</div>

We can see that when calling the showError() method we are passing the view name “custom_error_view” which will fetch the custom template and display the message accordingly.

5. Create the route to see the final output in browser.

$routes->get('customvalidationtemplate/form', 'Form::index');
$routes->post('customvalidationtemplate/form', 'Form::index');

6. We can see the error message displayed using the custom template on localhost url http://localhost:8080/customvalidationtemplate/form

Leave a Reply