Codeigniter Form Validation Library


Codeigniter Form Validation Library – Codeigniter provides predefined rules to validate the form fields that can be frequently used by loading the validation library. $this->load->library(‘form_validation’); is used to load the library. This library provides the optimized code for the form validation which reduces the effort & time to add the validations in form fields. Here in this tutorial, we are going to explain how to use form validation library.


Codeigniter form validation library | Load | Example

Let us understand how form validation library works in codeigniter with examples.

Load form validation class library

First load form validation library to use its functions, this library can be loaded simply as below-

How to load form validation library:

$this->load->library('form_validation');

Functions:-

There are following functions available in form validation library. Now we will explain one by one with example.

  • 1. Setting validation rules.
  • 2. Setting rules using an array and cascading rules.
  • 3. Prepping data.
  • 4. Re-populating the form.
  • 5. Callbacks: Your own validation methods.
  • 6. Setting error messages.
  • 7. Translating field names.

1. Setting validation rules

This method take three parameters :-

  • The field name.
  • The validation rule for this field
  • Set custom error message for current field(Optional field)

EXAMPLE

Here is simple example of setting validation rules.

Controller code:-

Your controller code now look like this:-

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

class form_check_controller extends CI_Controller
{
public function check(){
$this->load->view('validation_view');
}
public function index(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
   array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
 if ($this->form_validation->run() == FALSE)
    {
	$errors = validation_errors();
       $this->session->set_flashdata('error', $errors);
       redirect(base_url('index.php/form_check_controller/check'));	
}else{
    echo "successfully inserted";					
       }}}
?>

Views code:-

Your view code now look like this:-

<?php echo form_open('index.php/form_check_controller/index'); ?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>

Output will be like this:-

Codeigniter Form Validation Library

2. Setting rules using an array rule.

EXAMPLE

Here is simple example of Setting rules using an array rule.

Controller code:-

Your controller code now look like this:-

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class form_check_controller extends CI_Controller
{
	public function check()
	{
		$this->load->view('validation_view');
	}
public function arraycheck()
		{
			$this->load->helper('form');
            $this->load->library('form_validation');
			$array = array(array('field' => 'username',
                'label' => 'Username',
                'rules' => 'required'),
				array('field' => 'password',
                'label' => 'Password',
                'rules' => 'required',
                'errors' => array('required' => 'You must provide a %s.',
                ),),
		array(
                'field' => 'passconf',
                'label' => 'Password Confirmation',
                'rules' => 'required'),
		array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'required'
				));
		$this->form_validation->set_rules($array);
		if ($this->form_validation->run() == FALSE)
                {
		$errors = validation_errors();
	        $this->session->set_flashdata('error', $errors);    
		redirect(base_url('index.php/form_check_controller/check'));	
                }
                else
                {
		echo "successfully inserted";					
                }}}
?>

Output will be same like above code:-

3. Prepping data.

EXAMPLE

Here is simple example of Prepping data.

Controller code:-

Your controller code now look like this:-

$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[6]|max_length[15]');
            $this->form_validation->set_rules('password', 'Password', 'required',
                        array('required' => 'You must provide a %s.')
                );
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
            $this->form_validation->set_rules('email', 'Email', 'required');

This method is used for checking for length and matching both password fields.

Output will be like this:-

Codeigniter Form Validation Library

4. Re-populating the form.

EXAMPLE

Here is simple example of Re-populating the form.

view code:-

Your view code now look like this:-

<?php echo form_open('index.php/form_check_controller/arraycheck'); ?>

<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username');?>" size="50" />

<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password');?>" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf');?>" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>"size="50" />

<div><input type="submit" value="Submit" /></div>

</form>

This method is used for re-populated your form fields.

Output will be like this:-

Codeigniter Form Validation Library

5. Callbacks: Your own validation methods.

EXAMPLE

Here is simple example of Callbacks: Your own validation methods.

Controller code:-

Your controller code now look like this:-

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

class form_check_controller extends CI_Controller
{
public function check()
{
$this->load->view('validation_view');
}
public function index()
{
$this->load->helper('form');
 $this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
$this->form_validation->set_rules('email', 'Email','required');
$check = $this->form_validation->run();
if ($check == FALSE)
{
$errors = validation_errors();
$this->session->set_flashdata('error', $errors);
redirect(base_url('index.php/form_check_controller/check'));	
}
else
{
echo "successfully inserted";					
}}

public function username_check($check)
{
if ($check == '')
{
$this->form_validation->set_message('username_check', 'The {username} field can not be the word "null"');
return FALSE;
}
else
{
return TRUE;
}}}
?>

Output will be like this:-

Codeigniter Form Validation Library

6. Setting error messages.

EXAMPLE

Here is simple example of setting error messages.

Controller code:-

Your controller code now look like this:-

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class form_check_controller extends CI_Controller
{
public function check()
{
$this->load->view('validation_view');
}
public function index()
 {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_message('min_length', '{field} must have at least {param} characters.');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'rule1|rule2|rule3',
array('rule2' => 'Error Message on rule2 for this field_name'));
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
$this->form_validation->set_rules('email', 'Email','required');
$check = $this->form_validation->run();
if ($check == FALSE)
{
$errors = validation_errors();
$this->session->set_flashdata('error', $errors);
redirect(base_url('index.php/form_check_controller/check'));	
}
 else
{
echo "successfully inserted";					
}}}
?>

Output will be like this:-

Codeigniter Form Validation Library

7. Translating field names.

EXAMPLE

Here is simple example of translating field names.

Controller code:-

Your controller code now look like this:-

$this->form_validation->set_rules('username', 'lang:Your_name', 'required');

Output will be like this:-

Codeigniter Form Validation Library

Class reference

There are following types of class reference in form validation library.

1. Set rules.

set_rules($field[$label = ''[$rules = ''[$errors = array()]]])

This function is used to give permits you to set validation rules.

2. run.

run([$group = ''])

this method is used to run validation rules and return always boolean type result.

3. Set message.

set_message($lang[$val = ''])

We use this method for set the custom errors message..

4. Set error delimiters.

set_error_delimiters([$prefix = '<p>'[$suffix = '</p>']])

We use this method for set default prefix and suffix errors.

5. Set data.

set_data($data)

this method is used to set an array for validation.

6. Reset validation.

reset_validation()

This function is used to give permits to reset the validation.

7. Error array.

error_array()

This function is used to display error message in array form.

8. Error.

error($field[$prefix = ''[$suffix = '']])

We use this method for return a error message in specific fields.


Advertisements

Add Comment

📖 Read More