Skip to content
Home » News » Form validation in Codeigniter

Form validation in Codeigniter

The PHP framework Codeigniter has out of the box form validation which is pretty easy to implement. It requires code in 2 places; 1.) the form HTML in the view and 2.) the controller.

The view

In the view you can use wither Codeigniter’s form mark up or straightforward HTML form elements. Set the element name as required, e.g. ’email’ and then there are basically two modifications required:

<?= form_error('email') ?>

Where you would list to see the form error text displayed – the ‘Name is required’ type stuff.

And set the form element value to:

value="<?=set_value('email')?>"

so the user doesn’t have to fill out all the form fields again if the form does not validate

The controller

The first thing to do is load the validation library:

$this->load->library('form_validation');

Then we can set the validation rules. There should be one of these for each form field that needs checking:

$this->form_validation->set_rules('email', 'Your email address', 'required|trim|valid_email|min_length[4]');

Hopefully the rules in the example are fairly self-explanatory. There are a few more options which you can find here on the Ellis Labs website.

Next is the form error message format, i.e. how the text telling the user they have made a mistake is wrapped. This also allows you to style the CSS of the message:

$this->form_validation->set_error_delimiters('<div>', '</div>');

Now we just wait for the user to submit the form and when they do the handling part of the script  should be waiting with this:

if ($this->form_validation->run()){
    //process form code;
}
else{
    //display form again - this time error messages will appear;
}

The above code just checks what the user has entered against the rule set you defined and that’s it. Simples

An additional bonus is it also adds a layer of security with form fields able to be checked for data type.