How to Create Custom Validation Rule in CodeIgniter 4

Validation rules help to validate the form. You don’t need to write long if statement conditions for every <form > element.

CodeIgnite­r 4 comes equipped with nume­rous pre-defined validation rule­s. However, there­ may be instances where­ you require custom validation rules de­signed specifically for your application’s nee­ds.

In this article, we’ll discuss how to create­ such custom validation rules in CodeIgniter 4. By doing so, you can broade­n the framework’s validation capabilities and maintain data accuracy. Follow the­se steps to seamle­ssly handle distinct and diverse validation sce­narios while extending the­ validating functionality of your web applications alike.

How to create custom validation Rule in CodeIgniter 4


Table of Content

  1. Create a Custom Validation Class
  2. Update Validation.php
  3. Using Created Custom Validation Class in Controller
  4. Create Route
  5. Create a View
  6. Output
  7. Conclusion

1. Create a Custom Validation Class

I am creating a custom class for defining validations. I will create 2 methods to explain rule creation with and without parameter.

  • Create CustomValidation.php file in app/Config/ folder.
  • Create CustomValidation class.
  • In the class, every created method is a rule. So, name your method related to your validation.
  • Create 2 methods –
    • validusername() – This method is without a parameter type of rule. While using you do not need to pass extra parameter.

This method has 2 parameters –

      • $str – It has an element value.
      • $error – Using this you can return an error message.

Check if username has a valid value using preg_match(). If it has then return true otherwise return false and assign an error message to $error variable.

    • checkmax() – This method is a parameter type of rule. While using you need to pass an extra parameter.

This method has 3 parameters –

      • $str – It has element value.
      • $field – It has passed parameter value.
      • $data – Using this you can access other element values e.g. $data['minvalue'].

You cannot define $error as 4 parameter similar to the 1st method.

If $str value is less than $data[$field] then return false otherwise, return true.

Completed Code

<?php 
namespace Config;

class CustomValidation{

    public function validusername(string $str, ?string &$error = null): bool
    {

          $usernamePreg = "/^[a-zA-Z0-9]+$/";

          if( (preg_match($usernamePreg,$str))) {
                return true;
          }

          $error = "Please enter valid username";

          return false;

    }

    public function checkmax($str, string $field, array $data): bool
    {

         if($str < $data[$field]){
              return false;
         }

         return true;

    }

}

2. Update Validation.php

Need to mention created custom validation class in Validation.php for using it.

  • Open app/Config/Validation.php file.
  • Include Config\CustomValidation;.
  • Specify CustomValidation::class, in $ruleSets Array.

Completed Code

<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\CreditCardRules;
use CodeIgniter\Validation\FileRules;
use CodeIgniter\Validation\FormatRules;
use CodeIgniter\Validation\Rules;
use Config\CustomValidation; // Custom validation
 
class Validation extends BaseConfig
{
      // --------------------------------------------------------------------
      // Setup
      // --------------------------------------------------------------------

      /**
      * Stores the classes that contain the
      * rules that are available.
      *
      * @var string[]
      */
      public $ruleSets = [
           Rules::class,
           FormatRules::class,
           FileRules::class,
           CreditCardRules::class,
           CustomValidation::class, // Custom Validation
      ];

      /**
      * Specifies the views that are used to display the
      * errors.
      *
      * @var array<string, string>
      */
      public $templates = [
           'list' => 'CodeIgniter\Validation\Views\list',
           'single' => 'CodeIgniter\Validation\Views\single',
      ];

      // --------------------------------------------------------------------
      // Rules
      // --------------------------------------------------------------------
}

3. Using Created Custom Validation Class in Controller

  • Create PagesController Controller.
php spark make:controller PagesController
  • Create 2 methods –
    • index() – Load index view.
    • submitForm() – This method calls on form submit.

Define validation on submitted values –

      • name – Set required rule.
      • username – Set required rule and also set created custom validation rule – validusername.
      • minvalue – Set required and numeric rule.
      • maxvalue – Set required and numeric rule. Also, set custom validation rule with parameter – checkmax[minvalue]. Here, minvalue is <form > element name. You can also pass value instead of element name – checkmax[300].

If <form > is not validated then return to the page with validation messages otherwise, set SESSION flash and redirect to route('/').

Completed Code

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class PagesController extends BaseController
{
      public function index(){
           return view('index'); 
      }

      public function submitForm(){

           // Validation
           $input = $this->validate([
                'name' => 'required',
                'username' => 'required|validusername',
                'minvalue' => 'required|numeric',
                'maxvalue' => 'required|numeric|checkmax[minvalue]',
            ],[ 
                'maxvalue' => [
                     'checkmax' => 'Max value must be greater than min value',
                ]
           ]);

           if (!$input) { // Not valid

                $data['validation'] = $this->validator;

                return redirect()->back()->withInput()->with('validation', $this->validator);

           }else{ 

                // Set Session
                session()->setFlashdata('message', 'Submitted Successfully!');
                session()->setFlashdata('alert-class', 'alert-success');

           }
           return redirect()->route('/'); 
     }
}

4. Create Route

  • Open app/Config/Routes.php file.
  • Here, create 2 routes –
    • page/submitForm – Handle form submit.
$routes->get('/', 'PagesController::index');
$routes->post('page/submitForm', 'PagesController::submitForm');

5. Create a View

Create index.php file in app/Views/ folder.

Create a simple <form > and set action to <?=site_url('page/submitForm')?>. Displaying the error message of the custom validation rule is the same as any other built-in validation rule.

<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to create custom validation Rule in CodeIgniter 4</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" >
</head>
<body>

    <div class="container">
         <div class="row">
              <div class="col-md-6 mt-5" style="margin: 0 auto;">
                   <?php 
                   // Display Response
                   if(session()->has('message')){
                   ?>
                        <div class="alert <?= session()->getFlashdata('alert-class') ?>">
                             <?= session()->getFlashdata('message') ?>
                        </div>
                   <?php
                   }
                   ?>
                   <?php $validation = \Config\Services::validation(); ?>

                   <form method="post" action="<?=site_url('page/submitForm')?>">

                         <?= csrf_field(); ?> 

                         <div class="form-group mb-4">

                               <label class="control-label col-sm-2" for="name">Name:</label>

                               <div class="col-sm-10">
                                      <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="<?= old('name') ?>">
                               </div>

                               <!-- Error -->
                               <?php if( $validation->getError('name') ) {?>

                                    <div class='text-danger mt-2'>
                                          * <?= $validation->getError('name'); ?>
                                    </div>

                               <?php }?>
                         </div>

                         <div class="form-group mb-4">

                               <label class="control-label col-sm-2" for="username">Username:</label>
                               <div class="col-sm-10">
                                      <input type="text" class="form-control" id="username" placeholder="Enter Username" name="username" value="<?= old('username') ?>">
                               </div>

                               <!-- Error -->
                               <?php if( $validation->getError('username') ) {?>

                                    <div class='text-danger mt-2'>
                                         * <?= $validation->getError('username'); ?>
                                    </div>

                               <?php }?>
                         </div>

                         <div class="form-group mb-4">

                               <label class="control-label col-sm-2" for="minvalue">Min value:</label>
                               <div class="col-sm-10">
                                    <input type="text" class="form-control" id="minvalue" placeholder="Enter Min value" name="minvalue" value="<?= old('minvalue') ?>">
                               </div>

                               <!-- Error -->
                               <?php if( $validation->getError('minvalue') ) {?>

                                    <div class='text-danger mt-2'>
                                         * <?= $validation->getError('minvalue'); ?>
                                    </div>

                               <?php }?>

                         </div>

                         <div class="form-group mb-4">

                               <label class="control-label col-sm-2" for="maxvalue">Max value:</label>
                               <div class="col-sm-10">
                                    <input type="text" class="form-control" id="maxvalue" placeholder="Enter Max value" name="maxvalue" value="<?= old('maxvalue') ?>" >
                               </div>

                               <!-- Error -->
                               <?php if( $validation->getError('maxvalue') ) {?>

                                    <div class='text-danger mt-2'>
                                         * <?= $validation->getError('maxvalue'); ?>
                                    </div>

                               <?php }?>

                         </div>

                         <div class="form-group ">        
                              <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-info">Submit</button>
                              </div>
                         </div>

                   </form>

              </div>

         </div>

    </div>

</body>
</html>

6. Output

View Output


7. Conclusion

Creating custom validation rule­s in CodeIgniter 4 is esse­ntial to maintain the accuracy and authenticity of user input in we­b applications. This article outlines steps to he­lp you design rules tailored to your spe­cific requirements, providing fle­xibility for precise data validation and constraint enforce­ment. Improved application security and re­liability are two benefits of using this approach, e­nsuring that user input meets e­ssential guidelines.

With CodeIgnite­r 4’s validation system, users can handle comple­x validation scenarios with ease. This fe­ature provides an exce­llent tool that enables the­ enforcement of busine­ss rules and accurate formatting of user inputs. Code­Igniter 4 also allows for custom rule creation, e­nsuring endless possibilities in data che­cking. However, it is crucial to adhere­ to best practices when de­signing custom rules by ensuring code modularity, re­usability and proper documentation.

By mastering custom validation rule­s in CodeIgniter 4, one take­s a major stride towards constructing robust and secure we­b applications that handle user input validation effe­ctively. Armed with this understanding, individuals can confide­ntly build validation rules that align with their application’s unique re­quirements and offer use­rs an uninterrupted expe­rience.

If you found this tutorial helpful then don't forget to share.

Leave a Comment