CakePHP 4 Custom Validation Rule For Form Inputs

Share this Article
Reading Time: 11 minutes
423 Views

Validating a form is common to every application. Inside this article we will see CakePHP 4 Custom Validation rule for form elements. This will be step by step guide with example.

We will set an application, inside that we will create controller, model and a view file.

Let’s get started.


CakePHP 4.x Installation at System

Before installation of CakePHP we need some system requirements and it’s configuration. Here, System configuration means Server, PHP, Extensions, Database etc.

To know about basic installation settings to system, server to get this framework, you need to follow the guidelines of cakephp official document of. This document makes clear about what we need initially to set the things in a better way.

Additionally, we need composer at system. Composer is a tool which used to manage PHP dependencies, libraries etc .We will use composer to install CakePHP. So, first you need to install composer. If you have already installed or exists at your system, you can verify by command –

$ composer

If composer has been installed then this command will list all available commands of composer other wise you will get error something composer command not found.

Click here for the article – How to Install composer in ubuntu

Assuming Composer exists at system.

Let’s create a CakePHP project at system –

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.


Settings up Database & Application Connectivity

We need to create a database. Database table is going to store form data. We have created a database in PhpMyAdmin with the name of cakephp4_form. You can choose your own custom name of database.

Either you can use Manual tool of MySQL or you can create via MySQL command.

CREATE DATABASE cakephp4_form;

So, now we have a database. We need to create a table to store data. Let’s create a table with the name of tbl_users. This table again we can create via Manual interface of creating table or we can run a command to create it.

Create Table tbl_students –

CREATE TABLE IF NOT EXISTS tbl_users (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  name varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  email varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  phone_no varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

In table tbl_students we have columns as id, name, email & phone_no.

After creating database and table, now we need to configure and connect database with CakePHP 4 application.

Go to Project setup >> config (directory) >> app_local.php (file). Open this file to connect database.

'Datasources' => [
    'default' => [
      'host' => 'localhost',
      /*
               * CakePHP will use the default DB port based on the driver selected
               * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
               * the following line and set the port accordingly
               */
      //'port' => 'non_standard_port_number',

      'username' => 'root',
      'password' => 'root',

      'database' => 'cakephp4_form',
      /**
               * If not using the default 'public' schema with the PostgreSQL driver
               * set it here.
               */
      //'schema' => 'myapp',

      /**
               * You can use a DSN string to set the entire configuration
               */
      'url' => env('DATABASE_URL', null),
    ],
  ]

Successfully, we have now configured database connection with CakePHP 4 application.


Configuring Application Route

We need to create now application routes.

Go to Project Setup >> config (directory) >> routes.php (file). Open this file. 

$routes->scope('/', function (RouteBuilder $builder) {

    // Student Route
    $builder->connect('/add-user', ['controller' => 'Users', 'action' => 'addUser']);
  
});

Inside this route configuration, we can see we have created route for add student. Next, we need to create Controller. Because the actions for submitting form data we will do those stuff there.


Application Models & Entity Settings

We need to configure Model & Entity. Model contains the information of Table where we will do crud operations. Entity define the columns for value assignment.

To create a model –

Go to Project Setup >> src (directory) >> Model (directory) >> Table (directory).

Inside Table directory, create a file UsersTable.php. Inside this file copy and paste this given code.

<?php

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class UsersTable extends Table
{
    public function initialize(array $config): void
    {
        $this->setTable("tbl_users");
    }

    public function validationDefault(Validator $validator): Validator
    {
        // adding model validation for fields
        // Method #1
        $validator
            ->requirePresence("email")
            ->notEmpty("email", "Email field value is needed")
            ->add("email", [
                "valid_email" => [
                    "rule" => ["email"],
                    "message" => "Email Address is not valid",
                ],
                "min_length" => [
                    "rule" => ["minLength", 10],
                    "message" => "Invalid min length",
                ],
                "max_length" => [
                    "rule" => ["maxLength", 25],
                    "message" => "Invalid max length",
                ],
            ])
            ->requirePresence("phone_no")
            ->numeric("phone_no");

          /*Adding custom validation rules rules*/

          /*Method #2*/
          $validator
           ->add("name", "custom", [
           	 "rule" => function($value, $context){
             	   if(empty($value)){
                	 return "Name field should not be empty";
                 }

                 if(strlen($value) < 10){
                     return "Name field should not have min length less than 10";
                 }

                 if(strlen($value) > 20){
                     return "Name field should not exceed from 20 chars";
                 }
                 return true;
               }
            ]);

        return $validator;
    }
}

In Method #2, we have added custom validation rule over “name” form input field.

$validator
->add(“name”, “custom”, []);

This is a syntax to create a custom validation for any form input field. As, we already know $validator is an instance of Validator $validator.

By using this $validator instance we have called add() method. Inside this method, first parameter will be input field name attribute, second is the custom provider name. You can create your own name. Put anything, no issue. Next will be an array which will store rules and messages.

For default validation rules in CakePHP 4 for form inputs, we have a different article over this. You must go and read that too. Click here to go CakePHP 4 Form validation.

Next, we need to set Entity for Table definition about value assignments.

To Create an Entity –

Go to Project Setup >> src (directory) >> Model (directory) >> Entity (directory).

Inside Table directory, create a file User.php. Inside this file copy and paste this given code.

<?php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity
{
    protected $_accessible = [
        "name" => true,
        "email" => true,
        "phone_no" => true
    ];
}

Create Controller & It’s Methods

Controller is the file which controls the application flow. Inside this controller file we will create few methods.

To Create a Controller –

Go to Project Setup >> src (directory) >> Controller (directory)

<?php

namespace App\Controller;

use App\Controller\AppController;

class UsersController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel("Users");
    }

    public function addUser()
    {
        $user = $this->Users->newEmptyEntity();

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
          
            // when we submit this form via POST request type, automatically model
            // will take care of all validations what we have implemented in Model file
            // Custom validations will also apply automatically
            // Only you need to copy the whole code from here and apply to your project.
          
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }

        $this->set(compact("user"));
        $this->set("title", "Add User");
    }
}

Creating View File

To create view files we will create a folder with the name of controller in /templates directory.

Folder name – /templates/Users. Users is the name of the controller. We will keep all views inside this folder –

Source code /templates/Users/add_user.php

<div class="panel panel-primary">

   <div class="panel-heading">
        Add Student
   </div>
    <div class="panel-body">
        <?=
          $this->Form->create($user, [
              "class" => "form-horizontal",
              "id" => "frm-add-user",
          ])
        ?>
        <div class="form-group">
            <label class="control-label col-sm-2">Name:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
                            <?php
                              if ($this->Form->isFieldError('name')) {
                                  echo $this->Form->error('name');
                              }
                            ?>
            </div>
        </div>
       <div class="form-group">
            <label class="control-label col-sm-2" for="email">Email:</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
                <?php
                  if ($this->Form->isFieldError('email')) {
                      echo $this->Form->error('email');
                  }
                ?>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2">Phone no:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="phone_no" name="phone_no" placeholder="Enter phone no">
                <?php
                  if ($this->Form->isFieldError('phone_no')) {
                      echo $this->Form->error('phone_no');
                  }
                ?>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
        </div>
        <?=$this->Form->end()?>
    </div>
</div>

Test Application

As we have created all the needed file. To run application, back to browser and type project url into it.

Open project in terminal and start development server

$ bin/cake server -p 8765

This is the Form when you open the route http://localhost:8765/add-user

CakePHP 4 Form Validation Error
CakePHP 4 Form Validation Error
CakePHP 4 Form Validation Error
CakePHP 4 Form Validation Error

When we submit this form without filling any data then we should get errors. Still we don’t have used any CSS that’s why you will see all errors in black colored but make it some CSS for those errors.

More about validation and rules you can go to official documentation of CakePHP from validation rules here.

We hope this article helped you to learn CakePHP 4 Custom Validation Rule in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Leave a Comment