Working with Email Validation Rules in CodeIgniter 4

Share this Article
Reading Time: 5 minutes
601 Views

In Form submission validation is one of the major functionality we need to attach. Validation is either from client side and/or from server side as well. Inside this article we will see Email validation rules in codeigniter 4.

In CodeIgniter 4, there are several form validation properties available. So here, we will see about all email related validations like required, a valid email format and also we will see already existence of email address in database.

Also we have Mobile validation step by step guide in CodeIgniter 4 Click here to go.

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.


Turn Development Mode On

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.


Add Route

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

//...

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

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.

Open add-student.php and write this complete code into it.

<?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>
  • We will submit this form to controller. At controller end we will add form validation rules.
  • print_r($validation->listErrors() ); It prints all errors at once. But in case if we want single error per line

To Check any input field has any error or not

<p>
     Email : <input type="email" name="email" class="<?= ($validation->hasError('email')) ? 'is-error' : '' ?>"/>  
</p>
       

Here, inside above code we are checking the field error, it exists then we are adding a class into input field with the email field of is-error.

Print any specific field error

if ($validation->hasError('email')){
  
    echo $validation->getError('email'); // $validation is sent from controller
}

Create Controller

Next we need to create application 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.

Also we have the option to load any helper directly to any controller using helper() function.

$ php spark make:controller Student

It will create Student.php inside /app/Controllers folder. Open file 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|valid_email|is_unique[users.email]|min_length[6]",
				"mobile" => "required",
			];
			
			$messages = [
				"name" => [
					"required" => "Name is required"
				],
				"email" => [
					"required" => "Email required",
                    "valid_email" => "Email address is not in format",
                    "is_unique" => "Email address already exists"
				],
                "mobile" => [
					"required" => "Mobile Number is required"
                ],
			];
			
			if (!$this->validate($rules, $messages)) {

                return view("add-student", [
                    "validation" => $this->validator,
                ]);
            }else{
				
				// rest code to save data into database
			}
		}
		return view("add-student");
	}
}
  • if ($this->request->getMethod() == “post”) Checking request type
  • $rules = []; Define form validation rules
  • $messages = [] Define custom messages
  • if (!$this->validate($rules, $messages)) {} Validating add student form
  • “email” => “required|valid_email|is_unique[users.email]|min_length[6]” All email validation rules. required It checks email should be required, valid_email Email address pattern should be valid pattern, is_unique Email address should be unique in database, min_length Minimum length of email address should be not less than 6 characters.

More about validations over different different input fields, you can visit official document of validations of CodeIgniter 4.

We hope this article helped you to fix email validation rules 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

2 thoughts on “Working with Email Validation Rules in CodeIgniter 4”

Leave a Comment