Custom validation example in Codeigniter

You may also like to read:

Introduction

This tutorial shows how to work with custom validation in Codeigniter. We 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 we need to write a function which will be used as callback function for a particuler 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.

Prerequisites

Apache HTTP Server 2.4, PHP 7.3.5, Codeigniter 3.1.10

Example Implementation

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

Creating Project Directory

We will create a project root directory called codeIgniter-3.1.10-custom-validator. We will put extracted Codeigniter folders and files under the project root directory. Obviously the project context path will be codeIgniter-3.1.10-custom-validator.

Configuring Auto-load

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

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

Creating Controller Class

Create a controller file customvalidation.php under application/controllers with the following source code.

The below controller class holds the action method index() and triggers validation for our date input field.

We are 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('date', $data);
			} else {
				$this->load->view('date');
			}
		} else {		
			$this->load->view('date');
		}
	}
	
	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;
		}
		
	}
	
}

Creating View

Create a view file date.php under application/views folder.

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

Configuring Route

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';

Running the Application

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

Testing the Application

Home Page

custom validation example in codeigniter

Validation Error

custom validation example in codeigniter

Validation Success

custom validation example in codeigniter

Source Code

You can download source code.

That’s all. Thanks for reading.

Custom validation example in Codeigniter

Leave a Reply

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

Scroll to top