CodeIgniter Form Validation


CodeIgniter provides a form validation library that helps you to validate form fields by writing minimal code. You can set validation rules for each form field, and the library will automatically check the user’s input against these rules when the form is submitted.

To use the form validation library, you will first need to load it in your controller:


Next, you can set the validation rules for your form fields. You can set the rules using an array or by chaining them using the set_rules() function.

// Array syntax
$config = array(
    'field' => 'username',
    'label' => 'Username',
    'rules' => 'required'
    'field' => 'password',
    'label' => 'Password',
    'rules' => 'required',
    'errors' => array(
      'required' => 'You must provide a %s.',
    'field' => 'passconf',
    'label' => 'Password Confirmation',
    'rules' => 'required'
    'field' => 'email',
    'label' => 'Email',
    'rules' => 'required'


// Chaining syntax
$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');

You can also set custom error messages for each rule using the errors array.

Once you have set the validation rules, you can validate the form by calling the run() function:

if ($this->form_validation->run() == FALSE) {
  // Validation failed
} else {
  // Validation succeeded