Form Validation Library Codeigniter

Form Validation Library

The Codeigniter provides a form validation library that contains predefined rules to validate the form fields. It also helps in optimizing the form validation code, which reduces the effort and time of adding validation to the form field.

Load the Form Validation Class

Before using the form validation class in Codeigniter, you must load in the controller file by following the syntax:

$this -> load-> library ( ‘form_validation’ );

Class Reference

1. set_rules(): A set_rules() function is used to set the validation rule in the form fields.

 Syntax

set_rules($field [, $label = ‘’ [, $rules = ‘’ [, $errors = array() ] ] ] );

 It has four parameters

$field (string): It defines the form’s fields name.

$label (string): In this parameter, you can define the label name of the form’s field. Eg. Username, Password, etc. 

$rules: As the parameter represents, it is used to set the validation rules as a string list separated by a pipe “|”, or an array.

$errors: In this field, you can define a list of custom error messages.

2. run(): The run() function is used to execute a group of validation rules in the form, and if the validation is failed, it returns FALSE.

Syntax

run ( [ $group = ‘’ ]);

$group: It contains the name of the validation group to execute in a form.

3. set_message(): A set_message() function is used to set global or custom error messages in the form field.

Syntax

set_message ($lang [, $val = ‘’ ]);

It has two parameters

$lang: In this field, you can declare the fieldname for which you want to set an error message.

$val: It defines the error message; you want to appear on the form.

Example: It defines an error message for a particular form’s fieldname.

$this->form_validation->set_message('max_length', '{field} must have at least {param} characters.');

To display the error message globally in a form.

$this->form_validation->set_message( ‘rule’, ‘error Message’);

4. reset_validation(): It allows you to reset the form validation field, when you validate an array more than once. It should be called before validation of the new array.

5. set_data(): It is used to validate an array of data that set in the set_data() function.

Syntax

set_data( $data ); 

$data: It defines an array of data to validate in set_data() function.

6. error_array(): It is used to display all the error messages in an array.

7. has_rule():  The has_rule() function is used to verify that a rule is set for the specified field. And if the rule is set for that field, it returns a true value; otherwise, it shows false.

Syntax

has_rule ($field):

$field: It defines the name of the particular field to check the rule is present or not.

The Function of Form Validation

These are the following methods that are available in the form validation library for validating the form fields.

1. Setting validation rules in a form

A library allows you to set multiple validation rules in a given field. To set validation rules in a form field, you should use set_rules() method:

$this->form_validation->set_rules();

A set_rules() method contains three parameters as an input:

1. field name: The define field name should be unique and exactly the same as the form field.

2. Label name: A field name that you want to display in a form. Eg. Username, Email, etc.

3. And the last, Validation rule that is used for defining the rule of a particular field in a form.

4. (optional): It is an optional parameter to set custom error messages on any form fields. And if you don’t want to show any custom messages, it uses default error.

Example:

$this->form_validation->set_rules( ‘username’, ‘Username’, ‘required’ );
 $this->form_validation->set_rules( ‘pass’, ‘Password’, ‘required’ );
 $this->form_validation->set_rules( ‘email’, ‘Email’, ‘required’, array( ‘required’ => ‘Email should be unique’) ); 

Create a program uses of validation rules

Create a controller file Valid_form.php and save it in application/controller/Valid_form.php. After that, write the following program in the controller file.

Valid_form.php

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Valid_form extends CI_Controller {
         public function index()
         {
                 $this->load->helper(array('form', 'url'));
                 $this->load->library('form_validation'); 
                 $this->form_validation->set_rules('username', 'Full Name', 'required');
                 $this->form_validation->set_rules('pass', 'Password', 'required',
                         array('required' => 'You must provide an alphanumeric %s with special (@$) symbol.')
                 );
                 $this->form_validation->set_rules('email', 'Your Email-ID', 'required');
                 $this->form_validation->set_rules('cnfpass', 'Confirm Password ', 'required'); 
                 $this->form_validation->set_rules('mobno1', 'Contact No.', 'required');
                 $this->form_validation->set_rules('age', 'Customer Age ', 'required');
                 $this->form_validation->set_rules('gender', 'Gender', 'required');
                 if ($this->form_validation->run() == FALSE)
                 {
                         $this->load->view('view_form'); 
                 }
                 else
                 {
                         $this->load->view('success_form');
                 }
         }
 }
 ?> 

Create a view file view_form.php and save it in application/views/view_form.php. After that, write the following program in the controller file.

view_form.php

<html>
 <head>
 <title>Registration Form</title>
 </head>
 <body>
 <?php echo validation_errors('<div align="center" class="error" style="color:red">', '</div>'); ?>
 <?php echo form_open('Valid_form'); ?>
              <div align="center"> <h2>Registration Form </h2> </div> 
             <table align="center" width="60%" border="5" bordercolor="green"> 
 <tr> <td align="left" valign="top" width="50%"> 
             Full Name :<span class="error" style="color:red">* </span></td>
             <td > <input type="text" name="username" style= "width:100%"placeholder="Enter the Name" title="Please, Provide  Your Full Name !">   
 </td> </tr>
 <tr> <td align="left" valign="top" width="50%">
             Password : <span class="error" style="color:red">* </span> </td> 
 <td ><input type="password" placeholder="Enter the password" name="pass" style= "width:100%"title="Password should be alphanumeric">
 </td></tr>
 <tr><td align="left" valign="top" width="50%">
             Your Email-ID :<span class="error" style="color:red">* </span>  </td>
             <td > <input type="email" name="email" size="30" style= "width:100%" placeholder="Enter the email id" title="Please, Provide Your Personal Email-ID !">
 </td> </tr>
 <tr><td align="left" valign="top" width="50%">
             Confirm Password :<span class="error" style="color:red">* </span> </td>
             <td > <input type="password" name="cnfpass" style= "width:100%"
             placeholder="Confirm password should be same"  
             title="Please, Provide Your Password !">
 </td></tr>
 <tr> <td align="left" valign="top" width="50%">
             Contact No. :<span class="error" style="color:red">* </span>  </td>
             <td > <input type="number" name="mobno1" style= "width:100%" placeholder="83685********" title="Please, Provide only Your Personal Contect Number !">        
 </td> </tr>
 <tr>
 <td align="left" valign="top" width="50%">Customer Age :<span style="color:red">*</span>:</td>
                         <td > <input type="number" value="" placeholder="Your Age....." name="age" style= "width:100%"; > </td> </tr>
                         <tr> <td align="left" valign="top" width="50%">Gender<span class="error" style="color:red">* </span> </td>
                         <td >
 <input type="radio" name="gender" value="M" />Male
 <input type="radio" name="gender" value="F" />Female </td> </tr>
 </table>
 <div align="center"><input type="submit" value="Submit" style="color:Blue" />
 <input type="RESET" > </div>
 <?php echo form_close(); ?>
 </body>
 </html> 

Create a view file success_form.php and save it in application/views/success_form.php. After that, write the following program in the controller file.

success_form.php

<html>
 <head>
 <title>Success page</title>
 </head>
 <body>
 <h3>Your form has been successfully Submitted</h3>
 <p><?php echo anchor('Valid_form', 'Fill next form'); ?></p>
 </body>
 <html> 

Now execute the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/Valid_form, it shows the output, as shown below.

Form Validation Library

Now submit the incomplete registration form to display the error messages, and it shows the output, as shown below.

Form Validation Library

Note: If you have filled the complete form and clicked on the submit button, it shows "Your form has been submitted successfully".

2. Setting validation rules using an array

In the above method, we have used form validation rules to validate every field. Now in this method, we are setting the form validation rules using an array in action.

Syntax

$val = array(
             array(
                         ‘field’ => ‘username’,
                         ‘label’ => ‘Name’,
                         ‘rules’ => ‘required’
             ),
             array( 
                         ‘field’ => ‘pass’, 
                         ‘label’ => ‘Password’,
                         ‘rules’ => ‘required’,
                          ‘errors’ => array(‘
                                                 ‘required’ => ‘It must be alphanumeric with special symbols’,
                         ),
             ),
             array( 
                         ‘field’ => ‘mail’,
                         ‘label’ => ‘Email’,
                         ‘rules’ => ‘required’,
                          ‘errors’ => array(‘
                                                 ‘required’ => ‘Your email should be unique, 
                         ),
 )
 );
 $this->load->form_validation( $val ); 

Create a program uses of validation rules

Create a controller file Valid_form.php and save it in application/controller/Valid_form.php. After that, write the following program in the controller file.

Valid_form.php                    

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Valid_form extends CI_Controller {
         public function index()
         {
                 $this->load->helper(array('form', 'url'));
                 $this->load->library('form_validation');
                 $data = array(
                         array( 
                                 'field' => 'username',
                                 'label' => 'Full Name',
                                 'rules' => 'required'
                         ),
                         array(
                                 'field' => 'pass', 
                                 'label' => 'Password',
                                 'rules' => 'required',
                                 'errors' => array(
                 'required' => 'You must provide an alphanumeric %s with special (@$) symbol.',
                                 ),
                         ),
                         array(
                                 'field' => 'email',
                                 'label' => ' Your Email-ID',
                                 'rules' => 'required'
                         ),
                         array(
                                 'field' => 'cnfpass',  
                                 'label' => 'Confirm Password',
                                 'rules' => 'required',
                                 'errors' => array(
                 'required' => 'Confirm password should be matched with Password field',
                                 ),
                         ),
                         array(
                                 'field' => 'mobno1', 
                                 'label' => 'Contact No',
                                 'rules' => 'required'
                         ),
                         array(
                                 'field' => 'age',
                                 'label' => 'Customer Age',
                                 'rules' => 'required',
                                 'errors' => array(  
                                         'required' => '%s should be in number', ),
                         ),
                         array(
                                 'field' => 'gender',
                                 'label' => 'Gender',
                                 'rules' => 'required' 
                         )
                 );
                 $this->form_validation->set_rules($data);
                 if ($this->form_validation->run() == FALSE)
                 {
                         $this->load->view('view_form');
                 }
                 else
                 {
                         $this->load->view('success_form');
                 } 
         }
 }
 ?> 

Note: The view_form.php and success_form.php view files will remain the same in the views folder.

When you execute the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/Valid_form, it shows the output, as shown in the below image.

Form Validation Library

3. Cascading Rules

Using this rule, you can define multiple validation rules in each field of the form. It permits you to organize multiple rules using the pipe ( | ) symbol in the set_rules() function.

Syntax

$this->form_validation->set_rules (
                                                 ‘name’, ‘Name’,
                                                 ‘required|min_length[8]|max_length[20]|is_unique[name]’,
                                     array (
                                                 ‘required’ => ‘ You have not provided %s.’,
                                                 ‘is_unique’ => ‘ This %s already exixts.’
                                                 )
             );
 $this->form_validation->set_rules ( ‘pass’, ‘Password’,
                                                 ‘required|min_length[8]|max_length[20]|matches[] | regex_match[]|alpha’,
                         array ( ‘required’ => ‘You have not provided $s.’ ),
                                                             );
 $this->form_validation->set_rules( ‘email’, ‘Email’, required|valid_email|is_unique[email] ‘);

Create a controller file Valid_form.php and save it in application/controller/Valid_form.php. After that, write the following program in the controller file.

Valid_form.php

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Valid_form extends CI_Controller {
         public function index()
         {
                 $this->load->helper(array('form', 'url'));
                 $this->load->library('form_validation');
               $this->form_validation->set_rules(
                         'username', 'Full Name', 
                         'required|min_length[5]|max_length[12]|is_unique[username]',
                         array(
                                 'required'      => 'You have not provided %s.',
                                 'is_unique'     => 'This %s already exists.'
                         )
                 );
         $this->form_validation->set_rules('pass', 'Password', 
         'required|min_length[10]|max_length[20]|alpha_numeric',
         array( 
                 'required'      => 'You must provide an alphanumeric %s with special (@$) symbol.',
             'alpha_numeric' => "Password Should be alphanumeric"  )  
         );
         $this->form_validation->set_rules('email', 'Your Email-ID', 'required|valid_email|is_unique[users.email]');
         $this->form_validation->set_rules('cnfpass', ' Confirm Password', 'required|matches[pass]',
         array(  
                 'required' => 'Confirm password should be matched with password' 
         )
          );
         $this->form_validation->set_rules( 
                  'mobno1','Contact No',
                 'required|min_length[10]|max_length[11]|numeric',
                 array( 
                         'required' => 'Please provide your %s'
                 )
         );
         $this->form_validation->set_rules( 
                 'age', 'Customer Age',
               'required|greater_than_equal_to[1]|less_than[8]',
                  array( 
                         'required' => '%s should be in number' ) 
                 );
         $this->form_validation->set_rules('gender', 'Gender', 'required');   
             if ($this->form_validation->run() == FALSE)
                 {
                         $this->load->view('view_form');
                 }
                 else 
                 {
                         $this->load->view('success_form');
                 }
         }
 }
 ?> 

Note: The view_form.php and success_form.php view files will remain the same in the views folder.

When you execute the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/valid_form controller, it shows the output, as shown below.

Form Validation Library

You have to fill all the details of the Registration form and click on the submit button.

After that, it validates all form fields according to set form validation rules, and shows the error message for each field, as shown in the images below.

Form Validation Library

4. Prepping Data

Preparing data methods is similar to cascading rules. It is used to check validation rules such as trimming fields, checking length, and verifying that both password fields must match.

For eaxmple,

$this->form_validation->set_rules('username', 'Full name',                'trim|required|min_length[7]|max_length[20]');
       $this->form_validation->set_rules( 'pass', 'Password', 'trim|required|min_length[10]');
       $this->form_validation->set_rules( 'cnfpass', 'Confirm Password', 'trim|required|matches[pass]');
          $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); 

5. Display errors on individual fields

If you want to display an error message for each field instead of displaying a list of errors, you can use the form_error() function.

Create a controller file Valid_form.php and save it in application/controller/Valid_form.php. After that, write the following program in the controller file.

Valid_form.php

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');
 class Valid_form extends CI_Controller {
         public function index()
         {
                 $this->load->helper(array('form', 'url')); 
                 $this->load->library('form_validation');
 $this->form_validation->set_rules('username', 'Full Name', 'required');
                 $this->form_validation->set_rules('pass', 'Password', 'required',
                         array('required' => 'You must provide an alphanumeric %s with special (@$) symbol.')
                 );
                 $this->form_validation->set_rules('email', 'Your Email-ID', 'required');
                 $this->form_validation->set_rules('cnfpass', 'Confirm Password ', 'required'); 
                 $this->form_validation->set_rules('mobno1', 'Contact No.', 'required');
                 $this->form_validation->set_rules('age', 'Customer Age ', 'required');
                 $this->form_validation->set_rules('gender', 'Gender', 'required');
                 if ($this->form_validation->run() == FALSE)
                 {
                         $this->load->view('view_form');
                 } 
                 else
                 {
                         $this->load->view('success_form');
                 }
         }
 } 

Create a view file view_form.php and save it in application/views/view_form.php. After that, write the following program in the controller file.

view_form.php

<html>
 <head>
 <title>Registration Form</title>
 </head>
 <body>
 <?php echo form_open('Valid_form'); ?>
              <div align="center"> <h2>Registration Form </h2></div> 
                                      <fieldset width="80%">
                                      <legend>Details </legend>
             <table align="center" width="60%" border="0" bordercolor="green"> 
 <tr><td align="left" valign="top" width="50%"> 
             Full Name :<span class="error" style="color:red">* </span></td>
             <td > <span style="color:red"> <?php echo form_error('username'); ?> </span><input type="text" name="username" value="<?php echo set_value('colors[red]'); ?>" style= "width:100%"placeholder="Enter the Name"  
             title="Please, Provide  Your Full Name !">   
 </td> </tr>
 <tr><td align="left" valign="top" width="50%">
             Password : <span class="error" style="color:red">* </span> </td>
             <td > <span style="color:red"> <?php echo form_error('pass'); ?> </span> <input type="password" placeholder="Enter the password" name="pass" value="<?php echo set_value('pass'); ?>" style= "width:100%" title="Password should be alphanumeric">    
 </td></tr>
 <tr><td align="left" valign="top" width="50%">
             Your Email-ID : <span class="error" style="color:red">* </span>  </td>
             <td > <span style="color:red"> <?php echo form_error('email'); ?> </span> <input type="email" name="email" size="30" value="<?php echo set_value('email'); ?>" style= "width:100%" placeholder="Enter the email id"
                         title="Please, Provide Your Personal Email-ID !">   
 </td></tr> 
 <tr><td align="left" valign="top" width="50%">
             Confirm Password :<span class="error" style="color:red">* </span> </td>
             <td ><span style="color:red"> <?php echo form_error('cnfpass'); ?> </span> <input type="password" name="cnfpass" style= "width:100%" value="<?php echo set_value('cnfpass'); ?>"
             placeholder="Confirm password should be same" 
             title="Please, Provide Your Confirm Password!">    
 </td></tr>
 <tr><td align="left" valign="top" width="50%"> 
             Contact No. :<span class="error" style="color:red">* </span>  </td>
             <td > <span style="color:red"> <?php echo form_error('mobno1'); ?> </span> <input type="number" name="mobno1" value="<?php echo set_value('mobno1'); ?>" style= "width:100%" placeholder="83685********" title="Please, Provide only Your Personal Contact Number !">    
 </td> </tr>
 <tr>
 <td align="left" valign="top" width="50%">Customer Age :<span style="color:red">*</span>:</td>
                         <td ><span style="color:red"> <?php echo form_error('age'); ?> </span> <input type="date" value="<?php echo set_value('age'); ?>" 
                         placeholder="Your Age....." name="age" style= "width:100%"; ></td></tr>
 <tr> <td align="left" valign="top" width="50%">Gender<span class="error" style="color:red">* </span> </td>
 <td ><span style="color:red"> <?php echo form_error('gender'); ?> </span> 
 <input type="radio" name="gender" value="M"  value="<?php echo set_value('gender'); ?>" />Male
 <input type="radio" name="gender" value="F" value="<?php echo set_value('gender'); ?>" />Female </td> </tr>
 </table>
 <div align="center"><input type="submit" value="Submit" style="color:Blue" />
 <input type="RESET" ></div>
 </fieldset>
 <?php echo form_close(); ?>
 </body>
 </html> 

Create a view file success_form.php and save it in application/views/success_form.php. After that, write the following program in the controller file.

success_form.php

<html>
 <head>
 <title>Success page</title>
 </head>
 <body>
 <h3>Your form has been successfully Submitted</h3>
 <p><?php echo anchor('Valid_form', 'Fill next form'); ?></p>
 </body> 
 </html> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/valid_form controller; it shows the output, as shown below.

Form Validation Library

To show errors in individual fields, you must submit the form without filling the details in the registration form; it shows the output as shown below.

Form Validation Library

And if you have provided all the correct and complete details, it shows Your Registration fForm Validation Libraryorm is successfully filled, as shown in the below image.