Working with Email Validation Rules in CodeIgniter 4

Share this Article
Reading Time: 5 minutes
8,909 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.

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.


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


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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

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

  1. These are in fact enormous ideas in about blogging. You
    have touched some good factors here. Any way keep up wrinting.

Comments are closed.

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5