How to do form validation in codeigniter

Leave a Comment

Form validation in CodeIgniter using its form validation library

Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:
  1. A form is displayed. 
  2. You fill it in and submit it. 
  3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem. 
  4. This process continues until you have submitted a valid form.
In order to implement form validation you'll need three things:
  1. A View file containing a form.
  2. A View file containing a "success" message to be displayed upon successful submission.
  3. A controller function to receive and process the submitted data.
let's start with controller i.e. form_validation.php.


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

class form_validation extends CI_Controller {
 
 function __construct()
 {
  parent::__construct();
  $this->load->library('form_validation');
$this->load->helper('form');
 }

 function index()
 {
  $this->load->view('form_validation');
 }

 function check_validation()
 {
  $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|xss_clean');
  $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|xss_clean|matches[cpassword]');
  $this->form_validation->set_rules('cpassword', 'Confrim password', 'trim|required|min_length[5]|xss_clean');
  $this->form_validation->set_rules('website_url', 'Url', 'trim|required|xss_clean');
  
  if($this->form_validation->run()==true){
   print_r($this->input->post());
  }else{
   $this->load->view('form_validation');
  }
 }
}
Now lets create view file form_validation.php.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Form Validation In CodeIgniter</title>
 <style type="text/css">
 .warpper{
  width: 100%;
 }
 .warpper table{
  margin: 50px auto;
  text-align: center;
 }
 h1{
  text-align: center;
 }
 </style>
</head>
<body>
 <div class="warpper">
  <h1>Form Validation In CodeIgniter</h1>
  <?php echo form_open('form_validation/check_validation');?>
   <table border=1 cellpadding=5 cellspaceing=5>
    <tr>
     <td>Name</td>
     <td>
      <?php echo form_input('name');?>
      <?php echo form_error('name');  ?>
     </td>
    </tr>
    <tr>
     <td>Email Id</td>
     <td>
      <?php echo form_input('email');?>
      <?php echo form_error('email');  ?>
     </td>
    </tr>
    <tr><td>Password</td>
     <td>
      <?php echo form_password('password');?>
      <?php echo form_error('password');  ?>
     </td>
    </tr>
    <tr><td>Confrim password</td>
     <td>
      <?php echo form_password('cpassword');?>
      <?php echo form_error('cpassword');  ?>
     </td>
    </tr>
    <tr><td>website url</td>
     <td>
      <?php echo form_input('website_url');?>
      <?php echo form_error('website_url');  ?>
     </td>
    </tr>
    <tr colspan="2"><td><input type="submit"/></td></tr>
   </table>
  <?php echo  form_close();?>
 </div>
</body>
</html>


Explanation

The form (form_validation.php) is a standard web form with a couple exceptions:
  1. It uses a form helper to create the form opening. Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable in the event your URLs change.
  2. Controller has one function: construct() This function initializes the validation class and loads the form helper and load the form_validation library.
  3. Index(): This function loads view file.
  4. Run this code in using http://localhost/ci/form_validation/. You will get below screen.
  5. Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you'll see your success page.
  6. Form submitted on the check_validation function this function check various validation rules.If validation is true then i will print all post data else it will return to form will error massage.


Set Validation rules:

CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() function:

$this->form_validation->set_rules();


The above function takes three parameters as input:

  1. The field name - the exact name you've given the form field.
  2. A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file.
  3. The validation rules for this form field.

Some validation rules are here.
  • trim : This remove space from string both side(left and right).
  • required : Fields are compulsory.
  • min_length : Minimum length of the field is 5 character.
  • xss_clean : This removes malicious data.
  • valid_email : This will check user enter valid email or not.
  • matches : This will match one value to anotoher.
For more validation rule visit this link.   After all this if you submit your form then it will look like this



It's not look well so let's do some css to validation error.Modify check_validation function

function check_validation()
 {
  $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|xss_clean');
  $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|xss_clean|matches[cpassword]');
  $this->form_validation->set_rules('cpassword', 'Confrim password', 'trim|required|min_length[5]|xss_clean');
  $this->form_validation->set_rules('website_url', 'Url', 'trim|required|xss_clean');
  $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); // added new line
  if($this->form_validation->run()==true){
   print_r($this->input->post());
  }else{
   $this->load->view('form_validation');
  }
 }

Modify view file also add some css to file
<style type="text/css">
 .warpper{
  width: 100%;
 }
 .warpper table{
  margin: 50px auto;
  text-align: center;
 }
 h1{
  text-align: center;
 }
 .error{
  color: red;
 }
 </style>

After that if you submit the form then you will get screen like this screenshot.

Now its look little bit nice.If you inspect element those error then you get <div> with class error.

Changing the Error Delimiters: By default, the Form Validation class adds a paragraph tag (<p>) around each error message shown. You can either change these delimiters globally or individually.

  1. Changing delimiters Globally

    To globally change the error delimiters, in your controller function, just after loading the Form Validation class, add this:
    $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
    

    In this example, we've switched to using div tags.
  2. Changing delimiters Individually

    If you want to change error delimiter individually then you do this in view file when you write your form_error().
    <?php echo form_error('field name', '<div class="error">', '</div>'); ?>
    


    or

    from_error is used to show error individually.If you want to show all error at one place then you can use validation_errors().
    <?php echo validation_errors('<div class="error">', '</div>'); ?>
    

    If you want to use validation_errors() then you have to change your view file like this.

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="utf-8">
     <title>Form Validation In CodeIgniter</title>
     <style type="text/css">
     .warpper{
      width: 100%;
     }
     .warpper table{
      margin: 50px auto;
      text-align: center;
     }
     h1{
      text-align: center;
     }
     .error{
      color: red;
     }
     </style>
    </head>
    <body>
     <div class="warpper">
      <h1>Form Validation In CodeIgniter</h1>
      <?php echo form_open('form_validation/check_validation');?>
       <table border=1 cellpadding=5 cellspaceing=5>
        <tr>
         <td></td>
         <td>
          <?php echo validation_errors(); ?>
         </td>
        </tr>
        <tr>
         <td>Name</td>
         <td>
          <?php echo form_input('name');?>
         </td>
        </tr>
        <tr>
         <td>Email Id</td>
         <td>
          <?php echo form_input('email');?>
         </td>
        </tr>
        <tr><td>Password</td>
         <td>
          <?php echo form_password('password');?>
         </td>
        </tr>
        <tr><td>Confrim password</td>
         <td>
          <?php echo form_password('cpassword');?>
         </td>
        </tr>
        <tr><td>website url</td>
         <td>
          <?php echo form_input('website_url');?>
         </td>
        </tr>
        <tr colspan="2"><td><input type="submit"/></td></tr>
       </table>
      <?php echo  form_close();?>
     </div>
    </body>
    </html>
    
    
    After changing the view file if you submit form then it's show error like below image.

    error
If you submit your form using this value.

error


And submit form then it will accept all value and it's shows output like this :

error


but if you check that website url is wrong but it's accepted that value then how to handle this type of situation.No worries to handle this type of situation codeigniter introduce it's callback method.

Callbacks: Your own Validation Functions
The validation system supports callbacks to your own validation functions. This permits you to extend the validation class to meet your needs. For example, here we need to handle website url.so we modify the check_validation function.
function check_validation()
 {
  $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[5]|xss_clean');
  $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[5]|xss_clean|matches[cpassword]');
  $this->form_validation->set_rules('cpassword', 'Confrim password', 'trim|required|min_length[5]|xss_clean');
  $this->form_validation->set_rules('website_url', 'Url', 'trim|required|xss_clean|callback_checkwebsiteurl'); //modify this line
  $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
  if($this->form_validation->run()==true){
   echo "<pre>";
   print_r($this->input->post());
  }else{
   $this->load->view('form_validation');
  }
 }
Add new function in your controller file i.e form_validation.php
function checkwebsiteurl($string_url)
 {
        $reg_exp = "@^(http\:\/\/|https\:\/\/)?([a-z0-9][a-z0-9\-]*\.)+[a-z0-9][a-z0-9\-]*$@i";
        if(preg_match($reg_exp, $string_url) == TRUE){
         return TRUE;
        }
        else{
         $this->form_validation->set_message('checkwebsiteurl', 'URL is invalid format');
         return FALSE;
        }
 }

Reload your form and submit it with url mohit jain.You can see that the form field data was passed to your callback function for you to process.
To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix. If you need to receive an extra parameter in your callback function, just add it normally after the function name between square brackets, as in: "callback_foo[bar]", then it will be passed as the second argument of your callback function.
Note: You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.

Setting Error Messages


All of the native error messages are located in the following language file: language/english/form_validation_lang.php.
To set your own custom message you can either edit that file, or use the following function:

$this->form_validation->set_message('rule', 'Error Message');

Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.
If you include %s in your error string, it will be replaced with the "human" name you used for your field when you set your rules.
In the "callback" example above, the error message was set by passing the name of the function:
$this->form_validation->set_message('checkwebsiteurl', 'URL is invalid format');


Re-populating the form


Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. CodeIgniter offers several helper functions that permit you to do this.We need to change our view file to implement this function
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Form Validation In CodeIgniter</title>
 <style type="text/css">
 .warpper{
  width: 100%;
 }
 .warpper table{
  margin: 50px auto;
  text-align: center;
 }
 h1{
  text-align: center;
 }
 .error{
  color: red;
 }
 </style>
</head>
<body>
 <div class="warpper">
  <h1>Form Validation In CodeIgniter</h1>
  <?php echo form_open('form_validation/check_validation');?>
   <table border=1 cellpadding=5 cellspaceing=5>
    <tr>
     <td>Name</td>
     <td>
      <?php echo form_input('name',set_value('name'));?>
      <?php echo form_error('name');  ?>
     </td>
    </tr>
    <tr>
     <td>Email Id</td>
     <td>
      <?php echo form_input('email',set_value('email'));?>
      <?php echo form_error('email');  ?>
     </td>
    </tr>
    <tr><td>Password</td>
     <td>
      <?php echo form_password('password',set_value('password'));?>
      <?php echo form_error('password');  ?>
     </td>
    </tr>
    <tr><td>Confrim password</td>
     <td>
      <?php echo form_password('cpassword',set_value('cpassword'));?>
      <?php echo form_error('cpassword');  ?>
     </td>
    </tr>
    <tr><td>website url</td>
     <td>
      <?php echo form_input('website_url',set_value('website_url'));?>
      <?php echo form_error('website_url');  ?>
     </td>
    </tr>
    <tr colspan="2"><td><input type="submit"/></td></tr>
   </table>
  <?php echo  form_close();?>
 </div>
</body>
</html>

Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated.
We use set_value('field name') to re-populating the form.If we enter only website url wrong and submit then its look like this screenshot.All value are automatically re-populating the form.





Helpful links




Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .

0 comments:

Post a Comment

Powered by Blogger.