how to add validation rules for controller

How to add validation rules for a form and how to show if error occurs ?
we have created register.php in view that contains a form and created register.php in controllers like

class Register extends CI_Controller {

function __construct()
public function register()
function index()
{ $this->load->helper('form');
if (!empty($_POST['password']) && isset($_POST['confirm_password'])) {
$this->validator->add_rule('password', 'is_equal_to', 'Your password confirmation needs to match', array($_POST['password'], $_POST['confirm_password']));
$valid = $this->validator->validate($_POST);
$result = $this->Clients_model->entry_insert();
echo $result;

$fields = array();
$fields['first_name'] = array('required' => TRUE);
$fields['last_name'] = array('required' => TRUE);
$fields['email'] = array('required' => TRUE);


// will set the values of the fields if there is an error... must be after set_fields
$this->form_builder->display_errors = TRUE;
$this->form_builder->required_text = '*required fields';
$vars['form'] = $this->form_builder->render();

// use Fuel_page to render so it will grab all opt-in variables and do any necessary parsing
$page_init = array('location' => 'register');
$this->load->module_library(FUEL_FOLDER, 'fuel_page', $page_init);



but we dont know where to add validation rules.
we need to write validation rules for password match too


  • edited 1:19PM
    At first glance, it looks like you are doing things correctly. What seems to be happening? Are there any errors being returned by the validator object (you can use the get_errors() method on that object).

    If you need to create your own custom validation, you can create a function or a method on an object and pass it as the second parameter of the add_rule method on the validator object. If it is a method on an object, you use the array syntax "array($this, 'my_validation_method').
Sign In or Register to comment.