About Validation

Form validation is also important part of our website. In this case we check user input is correct or not. like

name field should not be blank
email field must be valid
phone field must be numeric and so on.

For this purpose Codeigniter provide validation library.

Step for validation

1- Add library in controller
2- create user input form in view
3- In controller create validation rules and run this check it return false or true.
4- If error exist then print error message on user form.


class Form extends CI_Controller {

public  function index() {


$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');

if ($this->form_validation->run() == FALSE) {
else {
echo "Validation success";

View - Show All Error in single message

<title>My Form</title>
<form name="frm"  action=""  method="post">
<?php  echo validation_errors(); ?>
<?php  echo form_open('form'); ?>
<input type="text"  name="name"  value=""  size="50" />
<input type="text"  name="email"  value=""  size="50" />
<input type="submit" value="Submit"/>

View - Show Error Individually

<title>My Form</title>
<?php  echo form_open('form'); ?>

<input type="text"  name="name"  value="<?php  echo set_value('name'); ?>" size="50"/>
<div style="color:#FF0000;"><?php  echo form_error('name'); ?></div>

<input type="text" name="email" value="<?php  echo set_value('email'); ?>" size="50" />
<div style="color:#FF0000;"><?php  echo form_error('email'); ?></div>

<input type="submit"  value="Submit"/>

<?php  echo form_close(); ?>

Custom Message

$this->form_validation->set_rules('name', 'Name', 'required',array('required' => 'Please enter user %s.'));

Please enter user name

Re-populating the form

When user submit form with some error message, then entered values not goes out.

<input type="text" name="name" value="<?php echo set_value('name'); ?>" size="50" />

Some common validation rule reference

Returns FALSE if the form element is empty.

Returns FALSE if the form element is shorter than the parameter value. min_length[6]

Returns FALSE if the form element is longer than the parameter value. max_length[12]

Returns FALSE if the form element is not exactly the parameter value. exact_length[8]

Returns FALSE if the form element does not contain a valid email address.

Returns FALSE if the form element contains anything other than alphabetical characters.

you can follow this link for more codeigniter rule reference