Form Validation And Setting Validation Rules in CI

Today we are going to  learn how to validate CI from and how to set validation rules in CI. Suppose we have a view which contains a form name signup_form.php like this

signup_form on view

signup_form on view

We need the proper validation on this form. For this first of all we have to  load

$this->load->helper(array(‘form’, ‘url’)); and
$this->load>library(‘form_validation’) on controller (here my controller name is login) or we can auto load this helper and library on the autoload file(application->config_>autoload).
Then we write method (here my method name is create_member) where we validate the form and set the rules.

Setting validation rules:
By using set_rules() method we set validation rules.
Syntax: $this->form_validation->set_rules();
The above function takes three parameters as input:

  • The field name - the exact name you’ve given the form field.
  • A part of string (Username) that you want to display on the error message.
  • The validation rules for this form field.
    Here is an example. In our controller (login.php), add this code just below the validation initialization function:

    $this->form_validation->set_rules(‘username’, ‘Username’, ‘required’);
    $this->form_validation->set_rules(‘password’, ‘Password’, ‘required’);
    $this->form_validation->set_rules(‘passconf’, ‘Password Confirmation’, ‘required’);
    $this->form_validation->set_rules(‘email’, ‘Email’, ‘required’);

    My controller looks like
    <?php
    class Login extends CI_Controller {
    function create_member()
    {
    $this->load->helper(array(‘form’, ‘url’));
    $this->load->library(‘form_validation’);
    $this->form_validation->set_rules(‘username’, ‘Username’, ‘required’);
    $this->form_validation->set_rules(‘password’, ‘Password’, ‘required’);
    $this->form_validation->set_rules(‘passconf’, ‘Password Confirmation’, ‘required’);
    $this->form_validation->set_rules(‘email’, ‘Email’, ‘required’);
    if ($this->form_validation->run() == FALSE)
    {
    $this->load->view(‘signup_form’);
    }
    else
    {
    $this->load->view(‘members_area‘);
    }
    }
    }
    ?>
    Here if the form validate successfully then load members_area view  otherwise load signup_form and display proper error message by 

    <div style=”color:red”><?php echo form_error(‘username’); ?></div>. The output look like:

    Error message

    Error message

    Here password and confirmation password field does not match. Hope it will  help you. Next we will discuss about database validation  using callbacks function  to check unique username. For more details please click here.

 

One thought on “Form Validation And Setting Validation Rules in CI

  1. Pingback: Callbacks: Our own Validation Functions | Technicise.com

Comments are closed.