how to add validation rules for controller

Hi,
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

<?php
class Register extends CI_Controller {

function __construct()
{
parent::__construct();
}
public function register()
{
$this->load->view('pages/main');
}
function index()
{ $this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Clients_model');
$this->load->library('session');
$this->load->library('form_builder');
$this->load->library('validator');
if(isset($_POST['action'])=='addclient'){
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;
if($result==1){redirect('register?message=success');}if($result==0){redirect('register?message=firstname');}
//redirect('registration?message=fail');
}


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

$this->form_builder->set_fields($fields);

// will set the values of the fields if there is an error... must be after set_fields
$this->form_builder->set_validator($this->validator);
$this->form_builder->set_field_values($_POST);
$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);
$this->fuel_page->add_variables($vars);
$this->fuel_page->render();

}

}

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

Comments

  • edited 8:45AM
    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.