Validate Mobile Number in CodeIgniter 4

Share this Article

When we create a form in any type of application like it will be an web, mobile etc. We need to validate form input fields. We can’t trust on the values entered by end users. Because sometimes we will receive valid values but 80-90% times we receive invalid too.

Inside this article we will see How can we validate mobile number in CodeIgniter 4 ? Inside this we will cover validations like required, mobile number format upto 10 characters and already exists in database.

To learn about Email validation in CodeIgniter 4, click here to go.

Additionally, while learning validation here also we will see step by step how to create custom rule in codeigniter 4. For above validations what we have discussed above we will do by creating our own validation classes.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Now, let’s configure database and application connectivity.

Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.

Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE tbl_students (
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)

Successfully, we have created a database and a table. Let’s connect with the application.

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi

Now, database successfully connected with application.

Create Route

To configure application routes, we need to open up the file Routes.php from /app/Config. This is the main routes config file where we will do all routes of application.

//.. Other routes

$routes->match(["get", "post"], "add-student", "Student::addStudent");

To remove /public/index.php from URL, you can find it’s complete resource here at this link.

Let’s create Model.

Set Application Model

Model is the face of application with the database. We need a Student Model which will do some basic model configuration.

Models are created at /app/Models. We are going to create StudentModel.php at this location.

$ php spark make:model Student --suffix

It will create StudentModel.php file at /app/Models folder.

Open StudentModel.php and write this following code into it.


namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_students';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];

Model is pointing tbl_students table. We have specified all the table columns into $allowedFields. If suppose we don’t specify then it restrict that missing field from insertion.

View File – Create User Form

As, we have taken fields as name, email, mobile. So with respective with these fields we need to set the user layout. Views templates will be created inside /app/Views/add-student.php

Inside this view file, at top header we have used session() service to collect session temporary data to show flash message. Flash message we will send from controller in keys of success and error.

  // To print success flash message
      <h3><?= session()->get("success") ?></h3>

  // To print error flash message
    <h3><?= session()->get("error") ?></h3>

  // To print error messages
    print_r($validation->listErrors() );


<form action="<?= base_url('add-student') ?>" method="post">
       Name: <input type="text" name="name" placeholder="Enter name"/>

       Email: <input type="email" name="email" placeholder="Enter email"/>

       Mobile: <input type="text" name="mobile" placeholder="Enter mobile"/>

     <button type="submit">Submit</button>
  • if(session()->get(“success”)){} – Checking for success key of temporary stored message.
  • session()->get(“success”) – Print session flash – success key message
  • if(session()->get(“error”)){} – Checking for success key of temporary stored message.
  • session()->get(“error”) – Print session flash – error key message
  • site_url(‘add-student’) – Site URL with add-student route
  • if(isset($validation)){} – Checking validation variable if it contains any error
  • print_r($validation->listErrors()); – Printing all error messages

Register Custom Rule in Application

When we do controller’s code, we will use a custom rule like mobileValidation, alreadyExists.

To store custom validation rules file, create a folder Validation in /app directory.

Let’s create a file with the name of MobileRules.php in /app/Validation folder.

Source code of /app/Validation/MobileRules.php

namespace App\Validation;
use App\Models\StudentModel;

class MobileRules{

  // Rule is to validate mobile number digits
  public function mobileValidation(string $str, string $fields, array $data){
    /*Checking: Number must start from 5-9{Rest Numbers}*/
    if(preg_match( '/^[5-9]{1}[0-9]+/', $data['mobile'])){
      /*Checking: Mobile number must be of 10 digits*/
      $bool = preg_match('/^[0-9]{10}+$/', $data['mobile']);
      return $bool == 0 ? false : true; 
      return false;

  // here we have created a custom rule method of already existence check of mobile number 
  public function alreadyExists(string $str, string $fields, array $data){
    $model = new StudentModel();
    $data = $model->where('mobile', $data['mobile'])

      return false; // mobile number already there

    return true; // mobile number not found

Next, we need to need to register this custom rule to application for use.

Open up the file /app/Config/Validation.php

# Add to Header
use App\Validation\MobileRules;

# Add here  
public $ruleSets = [
	//.. other rules

Application Controller Settings

Controller is the functional file. Firstly let’s load a helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

We will create application controller at /app/Controllers. Let’s create Student.php inside the given folder. Open project into terminal and type this spark command.

$ php spark make:controller Student

Write the following code into /app/Controllers/Student.php


namespace App\Controllers;

use App\Models\StudentModel;

class Student extends BaseController
	public function addStudent(){

		if($this->request->getMethod() == "post"){

			$rules = [
				"name" => "required",
				"email" => "required",
				"mobile" => "required|mobileValidation[mobile]|alreadyExists[mobile]",
                //"mobile" => "required|mobileValidation[mobile]|is_unique[]",
			$messages = [
				"name" => [
					"required" => "Mobile number required"
				"email" => [
					"required" => "Email required"
                "mobile" => [
					"required" => "Mobile Number is required",
					"mobileValidation" => "Invalid Mobile Number",
					"alreadyExists" => "Mobile number already exists"
			if (!$this->validate($rules, $messages)) {

                return view("add-student", [
                    "validation" => $this->validator,
				$dataObject = new StudentModel();

				$data = [
					"name" => $this->request->getVar("name"),
					"email" => $this->request->getVar("email"),
					"mobile" => $this->request->getVar("mobile"),


				$session = session();

				$session->setFlashdata("success", "Data saved successfully");

				return redirect()->to(site_url("add-student"));
		return view("add-student");
  • if ($this->request->getMethod() == “post”) Checking request type
  • $rules = []; Define form validation rules
  • required|mobileValidation[mobile]|alreadyExists[mobile] Custom validation rules defined above. required Required rule for mobile number, mobileValidation It is of valid pattern for mobile number, alreadyExists this is for custom rule for checking already exists or not. Also we can do this by a validation rule as is_unique[]
  • $messages = [] Define custom messages
  • if (!$this->validate($rules, $messages)) {} Validating add student form
  • $dataObject = new StudentModel(); Creating student model instance
  • $session = session(); Creating a session instance for flashdata.

We hope this article helped you to fix Validate Mobile Number in CodeIgniter 4 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.

Find More on CodeIgniter 4 here

Leave a Comment