Custom Validation Example In Codeigniter 3

Table of Contents

Introduction

This tutorial shows how to work with custom validation in Codeigniter. You need many times that a field has to be validated against some type of values but built-in features do not provide all kind of validation pattern, so you need to write a function which will be used as callback function for a particular input field for validation purpose. The below example validates the date field and if the date is invalid then it displays an appropriate error message to the user.

This example is for only testing purpose and will guide you how you can use this idea to apply to a broader range of custom validations. You might various types of data to be input for your input fields where you need to validate before you process input data for your business.

Related Post:

Prerequisites

Apache HTTP Server 2.4 (Optional), PHP 7.4.3 – 7.4.27, Codeigniter 3.1.11

Go through the following steps to implement custom validation example in Codeigniter.

Project Directory

I will create a project root directory called codeIgniter-custom-validator. I will put extracted Codeigniter folders and files under the project root directory.

I may not mention the project root directory in the subsequent sections while but I will assume that I am creating the required files/folders with respect to the project root directory.

Auto-load Configuration

Now modify application/config/autoload.php file for auto-loading urlfileform_validation.

$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('url', 'form');

Controller Class

Create a controller file CustomValidation.php under application/controllers folder with the following source code. The below controller class contains the action method index() and triggers validation for our date input field.

I am also calling a CodeIgniter callback function to validate our field with our own validation or custom validation.

Similarly if you have any other fields where CodeIgniter’s built-in validation is not sufficient then you can create your own callback function to validate your fields.

The view file is loaded using index() method.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class CustomValidator extends CI_Controller {
	
	function __construct() {
        parent::__construct();
    }

	function index() {
		
		if ($this->input->post('verify')) {
			$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required|max_length[10]|callback_is_start_date_valid');
			
			if ($this->form_validation->run()) { //validation ok
				//process your business
				//for testing purpose only
				$data['msg'] = 'Validation passed!';
				$this->load->view('validation', $data);
			} else {
				$this->load->view('validation');
			}
		} else {		
			$this->load->view('validation');
		}
	}
	
	function is_start_date_valid($date) {

		if (date('Y-m-d', strtotime($date)) == $date) {
			return TRUE;
		} else {
			$this->form_validation->set_message('is_start_date_valid', 'The {field} must be in format "yyyy-mm-dd"');
			return FALSE;
		}
		
	}
	
}

View File

Create a view file validation.php under application/views folder. This view file contains the input field for entering the date value. In fact user can enter any value in this input field. Once user enters the value and clicks on the Submit button you need to validate the value to check whether it is a date in a given format otherwise throw an error.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>CodeIgniter Custom Validator Example</title>

	<style type="text/css">

	::selection { background-color: #E13300; color: white; }
	::-moz-selection { background-color: #E13300; color: white; }

	body {
		background-color: #fff;
		margin: 40px;
		font: 13px/20px normal Helvetica, Arial, sans-serif;
		color: #4F5155;
	}

	h1 {
		color: #444;
		background-color: transparent;
		border-bottom: 1px solid #D0D0D0;
		font-size: 19px;
		font-weight: normal;
		margin: 0 0 14px 0;
		padding: 14px 15px 10px 15px;
	}
	
	#body {
		margin: 0 15px 0 15px;
	}


	#container {
		margin: 10px;
		width: 600px;
		border: 1px solid #D0D0D0;
		box-shadow: 0 0 8px #D0D0D0;
	}
	</style>
</head>
<body>

<div id="container">
	<h1>CodeIgniter Custom Validator Example</h1>

	<div id="body">
		<p>
			<?php
				echo form_open($this->uri->uri_string());
				
				if (validation_errors()) {
					echo '<div style="color:red">';
					echo validation_errors();
					echo '</div>';
				}
				
				if (isset($msg)) {
					echo '<div style="color:green">';
					echo $msg;
					echo '</div>';
				}
			?>
			<div>
				<label for="exp_start_date">Start Date <span style="color:red">(required)</span></label>
				<input id="start_date" name="start_date" class="text" value="<?php echo set_value('start_date'); ?>" type="text" />
			</div>
			<div>
				<input name="verify" id="verify" class="button verify" value="Verify" type="submit" />
			</div>
			<?php
				echo form_close();
			?>
		</p>
	</div>
</div>

</body>
</html>

Route Configuration

Update default controller to point your controller to load your page on context URL.

Modify the file application/config/routes.php to have below value.

$route['default_controller'] = 'customvalidator';

Testing Custom Validation

Make sure to run your Apache HTTP Server 2.4 so that you will be able to access your application on browser.

Home Page

The input field is required. So you can submit the page without entering input value but you will see an error.

codeigniter custom validation

Validation Error

On validation error you will get below error message. You can click and check without entering any value or entering invalid date value or non-date value.

codeigniter custom validator
custom validation codeigniter

Validation Success

If you input the correct format for the date value then you will see success message on page submit.

validation in codeigniter

Source Code

Download

1 thought on “Custom Validation Example In Codeigniter 3

Leave a Reply

Your email address will not be published. Required fields are marked *