CodeIgniter Form Validation with Example

CodeIgniter Form Validation with Example

User interaction with the application is majorly done via Forms, which is then submitted to the database. It is mandatory to get the data correct while filling up the form so that no gibberish data may fall into the database which makes the database junky.

The process of Form Validations helps in ensuring that the data that is submitted is correct to store and process. Form Validations on server-side scripting are a little bit complex to handles but Codeigniter handle the form validations much easily as it is having built-in library functions to create forms validations.

Handling Form Validations in Codeigniter

Do the following in application/config/autoload.php

Load the form helper in the autoload helper array.

$autoload['helper'] = array('form', 'url');

Include form_validation library inside autoload libraries array.

$autoload['libraries'] = array('form_validation');

You can also load the helper and libraries inside the FormController.php methods by using:

Enter the credentials name and email, if you enter name and email it will show the success page else give a validation error name and email is required.

Output

Explanation:

form_validaton library in CodeIgniter helps in checking the type of error which has various validation rules in it. We are using the required rule above which is a validation of a required field. (for more validation rule reference checkout Codeigniter user guide)

Form helper helps in the form task i.e. in system/helpers/form_helper.php which helps out with some form functions.

In form.php view, the validation_errors(); function shows the form validation error which occurs during wrong credentials input.

In FormController.php $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('email', 'Email', 'required'); Sets the validation rule for the name and email field inside the form. Here parameters passed by set_rules(); are set_rules('name_field', 'validation_for' , 'type_of_rule')

If the above condition is false i.e. the required condition is not satisfied and form is not filled up then the validation is shown with the type of validation in the form view. If it is true then it will redirect to the success page.