Custom Validation in CodeIgniter Framework


In CodeIgniter Project, Open autoload.php file in config folder. Add form and url helper to helper config as below:

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

In CodeIgniter Project, Open autoload.php file in config folder. Add form_validation library to libraries config as below:

$autoload['libraries'] = array('form_validation');




In CodeIgniter Project, Open config.php file in config folder. Set value for base_url config as below:

$config['base_url'] = 'http://localhost:9092/LearnCodeIgniterWithRealApps/';

Create new PHP file named demo.php in controllers folder as below:

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

class Demo extends CI_Controller
{

    public function index()
    {
        $this->load->view('demo/index');
    }

    function save()
    {
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]|max_length[12]|callback_check_username');
        $this->form_validation->set_rules('website', 'Website', 'trim|callback_valid_url');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('demo/index');
        } else {
            $data['account'] = $_POST;
            $this->load->view('demo/success', $data);
        }
    }

    function valid_url($str)
    {
        $pattern = "|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i";
        if (! preg_match($pattern, $str)) {
            $this->form_validation->set_message('valid_url', 'The URL you entered is not correctly formatted.');
            return FALSE;
        }
        return TRUE;
    }

    function check_username($str)
    {
        if ($str == 'acc1') {
            $this->form_validation->set_message('check_username', 'Username already exists');
            return FALSE;
        }
        return TRUE;
    }
}

In CodeIgniter Project, Open routes.php file in config folder. Set value for default_controller as below:

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




Create new folder named demo in views folder. In this folder, create new views as below:

Create new PHP file named index.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Demo Page</title>
		<style type="text/css">
		  .error {
		      color: red;
		  }
		</style>
	</head>
	<body>

		<h3>Register</h3>

		<?php echo validation_errors('<p class="error">', '</p>'); ?>

		<?php echo form_open('demo/save'); ?>
        	<table cellpadding="2" cellspacing="2">
        		<tr>
        			<td>Username</td>
        			<td>
        				<input type="text" name="username" value="<?php echo set_value('username'); ?>"/>
        			</td>
        			<td><?php echo form_error('username', '<span class="error">', '</span>'); ?></td>
        		</tr>
        		<tr>
        			<td>Website</td>
        			<td>
        				<input type="text" name="website" value="<?php echo set_value('website'); ?>"/>
        			</td>
        			<td><?php echo form_error('website', '<span class="error">', '</span>'); ?></td>
        		</tr>
        		<tr>
        			<td>&nbsp;</td>
        			<td>
        				<input type="submit" value="Save"/>
        			</td>
        		</tr>
        	</table>
		<?php echo form_close(); ?>

	</body>
</html>

Create new PHP file named success.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
    <head>
        <title>Success Page</title>
    </head>
    <body>

    	<h3>Account Info</h3>

    	<table cellpadding="2" cellspacing="2" border="1">
    		<tr>
    			<td>Username</td>
    			<td><?php echo $account['username']; ?></td>
    		</tr>
    		<tr>
    			<td>Website</td>
    			<td><?php echo $account['website']; ?></td>
    		</tr>
    	</table>

    </body>
</html>




Access index action in Demo controller with following url: http://localhost:9092/LearnCodeIgniterWithRealApps/demo/index

Output

Click Save button submit form to Save action in Demo controller with invalid data as below:

Click Save button submit form to Save action in Demo controller with valid data

Output

I recommend you refer to the books below to learn more about the knowledge in this article: