CodeIgniter Form Validation with Example

Home > Codeigniter Tutorial > CodeIgniter Form Validation with Example

Best PHP Live Project Based Winter Training in Noida for more details click here



CodeIgniter  Form Validation with Example

User interaction with the application is majorly done via Forms, which is then submitted to the database. It is mandatory to get the data correct while filling up the form so that no gibberish data may fall into the database which makes the database junky.

The process of Form Validations helps in ensuring that the data that is submitted is correct to store and process. Form Validations on server-side scripting are a little bit complex to handles but Codeigniter handle the form validations much easily as it is having built-in library functions to create forms validations.

Handling Form Validations in Codeigniter

Do the following in application/config/autoload.php

Load the form helper in the autoload helper array.

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

Include form_validation library inside autoload libraries array.

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

You can also load the helper and libraries inside the FormController.php methods by using:

public function __construct()
{
parent::__construct();
$this->load->helper(array('form'));
$this->load->library(array('form_validation'));
}

While $autoload[ ] array helps in loading the library or helper automatically when the application starts as it is a good practice to minimize the line of codes by not repeatedly using same code.

Create View

Make a view file form.php inside application/views/ This page will display the form and which will be validated.

<html>
<head>
<title>Form</title>
</head>
<body>
  <form>
  	<?php echo validation_errors(); ?>  
  	<h5>Name</h5> 
  	<input type = "text" name = "name" value = "<?php echo set_value('name'); ?>" />  
	<h5>Email</h5> 
  	<input type = "email" name = "email" value = "<?php echo set_value('email'); ?>" />  
  	<div><input type = "submit" value = "Submit" /></div>  
  </form>  
</body>
</html>

Also make a success.php page inside application/views/ to redirect form success.

<html>
<head>
<title>Success</title>
</head>
<body>
  <h1>Form Submitted Successfully</h1>
</body>
</html>

Create Controller

Create a FormConrtoller.php inside application/controller/
This page will show the form validations or print success message.

<?php
  class FormController extends CI_Controller
  {
	public function __construct()
	{
	parent::__construct();
	$this->load->helper(array('form'));
	$this->load->library(array('form_validation'));
	}
   public function form()
   {
        $this->form_validation->set_rules('name','Name','required'); 
		$this->form_validation->set_rules('email','Email','required');

	   if ($this->form_validation->run() == FALSE) 
		{
			$this->load->view('form');
		} 
		else 
		{
			$this->load->view('success');
		}
    }
  }
?>

Now go to the browser and open the project :

localhost/project_folder/formcontroller/form

Enter the credentials name and email, if you enter name and email it will show the success page else give a validation error name and email is required.

Output

Explanation:

  • form_validaton library in CodeIgniter helps in checking the type of error which has various validation rules in it. We are using the required rule above which is a validation of a required field. (for more validation rule reference checkout Codeigniter user guide)
  • Form helper helps in the form task i.e. in system/helpers/form_helper.php which helps out with some form functions.
  • In form.php view, the validation_errors(); function shows the form validation error which occurs during wrong credentials input.
  • In FormController.php $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('email', 'Email', 'required'); Sets the validation rule for the name and email field inside the form. Here parameters passed by set_rules(); are set_rules('name_field', 'validation_for' , 'type_of_rule')
  • If the above condition is false i.e. the required condition is not satisfied and form is not filled up then the validation is shown with the type of validation in the form view. If it is true then it will redirect to the success page.

Display Individual Error for every Field

<html>
<head>
<title>Form</title>
</head>
<body>
  <form method="post">
  	<h5>Name</h5> 
  	<input type = "text" name = "name" value = "<?php echo set_value('name'); ?>" />  
	<?php  if(form_error('name'))
	{ 
	echo "<span style='color:red'>".form_error('name')."</span>";
	} 
	?>
	<h5>Email</h5> 
  	<input type = "email" name = "email" value = "<?php echo set_value('email'); ?>" />  
  	<?php  if(form_error('email'))
	{ 
	echo "<span style='color:red'>".form_error('email')."</span>";
	} 
	?>
	
	<div><input type = "submit" value = "Submit" /></div>  
  </form>  
</body>
</html>
Output

Set Multiple Rules for a text box(Required, Minlength, Maxlength)

$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[4]|max_length[10]');

Set Multiple Rules for a text box(Required, valid email address)

$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');

Total Downloads : 2

Login / Register To Download