How To Validate Mobile Number in CodeIgniter 4 Tutorial

Reading Time: 9 minutes
10,793 Views

Inside this article we will see the concept i.e How To Validate Mobile Number in CodeIgniter 4 Tutorial. Article contains the classified information about Phone number validation in PHP Codeigniter.

Inside this we will cover validations like required, mobile number format up to 10 characters and already exists in database.

When we create a form in any type of application like it will be inside web, mobile apps 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.

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.

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

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.

Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Create Database Table

Next, we need a table. That table will be responsible to store data.

Let’s create table with some columns.

CREATE TABLE tbl_students (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(120) DEFAULT NULL,
    email varchar(120) DEFAULT NULL,
    mobile varchar(45) DEFAULT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


Add Route

Open Routes.php from /app/Config folder. Add this route into it.

//...

$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.

Create Model

Back to terminal and run this spark command to create a model file.

$ 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.

<?php

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        = [
		"name",
		"email",
		"mobile"
	];

	// 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.

Create View Layout

Create add-student.php inside /app/Views folder.

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.

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

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

  // To print error messages
  if(isset($validation)){
    
    print_r($validation->listErrors() );
  }

?>

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

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

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

   <p>
     <button type="submit">Submit</button>
   </p>
</form>
  • 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

<?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; 
      
    }else{
      
      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'])
                  ->first();

    if(!$data)
      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
	MobileRules::class,
];

Create Controller

Loading url Helper

Open BaseController.php from /app/Controllers folder.

Search for $helpers, inside this helpers array simply add this url helper.

protected $helpers = ["url"];

This url helper will load base_url() and site_url() functions.

$ php spark make:controller Student

It will create Student.php inside /app/Controllers folder. Open and write this complete code into it.

<?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[tbl_students.mobile]",
			];
			
			$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,
                ]);
            }else{
				
				$dataObject = new StudentModel();

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

				$dataObject->insert($data);

				$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[tbl_students.mobile]
  • $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 learn about How To Validate Mobile Number in CodeIgniter 4 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more