CodeIgniter 4 Form Validation & Form Submit with Example
โก Smart Summary
CodeIgniter 4 Form Validation checks user input before it is processed. Forms are built with the form helper, and the built-in validation library sets rules such as required, numeric, and is_unique, then displays errors and repopulates sticky fields when validation fails.

Form in CodeIgniter 4
Forms provide a way for users to interact with the application and submit data. A form can be used for a contact-us form that a visitor to the website can fill in and send the information to us. The information received is usually stored in the database or sent via email.
HTML Form Structure
The following code shows the structure of a typical HTML form.
<form id="frmUsers" name="frmUsers" method="POST" action="create_user.php"> <input type="text" id="user_id" name="user_id"> <input type="password" id="password" name="password"> <input type="submit" value="Submit"> </form>
Here:
- <form>โฆ</form> are the opening and closing tags of the form. The id and name attributes specify the name and id of the form. The method attribute specifies the HTTP verb to be used, usually POST.
- <inputโฆ> specifies the form elements. The name attribute is the variable name submitted to the backend server for processing.
CodeIgniter Form Helper
HTML is easy to understand and write, but CodeIgniter makes things even simpler. CodeIgniter has built-in functions to create HTML forms. Let us consider the following CodeIgniter form code that uses the form helper to create a form:
<?php echo form_open('create_user.php', ['id' => 'frmUsers']); echo form_label('User Id', 'user_id'); echo form_input(['name' => 'user_id']); echo form_label('Password', 'password'); echo form_input(['type' => 'password', 'name' => 'password']); echo form_submit('btnSubmit', 'Create User'); echo form_close(); ?>
Here:
- echo form_open(‘create_user.php’, [‘id’ => ‘frmUsers’]); creates the form’s opening tag, sets the method to POST, and sets the action URL to create_user.php.
- echo form_label(‘User Id’, ‘user_id’); creates a label that reads User Id for the input field named user_id.
- echo form_input([‘name’ => ‘user_id’]); creates a text input field named user_id.
- echo form_submit(‘btnSubmit’, ‘Create User’); creates a submit button with the label Create User.
- echo form_close(); closes the form.
As you can see, form helpers make it easy to create forms using pure PHP. By passing attributes to the form helper methods, we can customize the HTML generated for the form. The code above generates the following HTML form code:
<form action="http://localhost:3000/index.php/create_user.php" id="frmUsers" method="post" accept-charset="utf-8"> <label for="user_id">User Id</label> <input type="text" name="user_id" value=""/> <label for="password">Password</label> <input type="password" name="password" value=""/> <input type="submit" name="btnSubmit" value="Create User"/> </form>
The biggest advantage of using the form helper is that it generates semantically correct code that adheres to the HTML standards. You can refer to the official CodeIgniter documentation for more details: https://codeigniter.com/user_guide/helpers/form_helper.html.
CodeIgniter Form Example
After covering the basics of CodeIgniter, let us get back to our tutorial project, which we have been working on throughout this CodeIgniter tutorial series. In summary, the tutorial project builds a contacts management app that stores the details in the database.
Create Contact
In the previous tutorial, we created routes for our application and simple views. Open application/views/contacts/create.php and modify the code for create.php as follows:
<div class="column">
<h2 class="title">Create Contact</h2>
<form action="<?= base_url('contacts/store') ?>" method="POST">
<div class="field">
<label class="label">Contact Name</label>
<div class="control">
<input id="name" name="name" class="input" type="text" placeholder="Type the contact name">
</div>
</div>
<div class="field">
<label class="label">Contact Number</label>
<div class="control">
<input id="name" name="name" class="input" type="text" placeholder="Type the contact number">
</div>
</div>
<div class="field">
<label class="label">Email Address</label>
<div class="control">
<input id="email" name="email" class="input" type="email" placeholder="Type the email address">
</div>
</div>
<div class="field is-grouped">
<div class="control">
<button class="button is-link">Save Contact</button>
</div>
</div>
</form>
</div>
Note: the code above uses plain HTML to create the form. Let us now see how our form looks in the web browser. Load the following URL into your web browser: http://localhost:3000/contacts/create. If you have been building the tutorial project, you should see the following:
Form Validation in CodeIgniter
Validation plays a very critical role when processing data from forms. Suppose a user is signing up on a website; we want to make sure they fill in their required details and a valid email address. If we are working with date values, we want to make sure the date ranges are valid, so we would not accept a date with 32 days in a month.
Validation solves these problems. CodeIgniter validation is done on two fronts when working with web applications.
Client-side validation is done in the web browser, usually with HTML and JavaScript. It improves performance because everything is done on the client, so there is no need to submit the data to the server. The disadvantage is that the user has control over it; if you rely on JavaScript to validate and the user disables JavaScript, your validation will fail.
Server-side validation is done on the server. The downside is that the user has to submit the data to the server and wait for the response, which uses network resources and may degrade performance. The major advantage is greater control and the assurance that your validation rules work even if the user disables JavaScript.
A better strategy is to use client-side validation as the primary strategy and server-side validation as a fallback mechanism.
Adding Form Validation Rules
CodeIgniter has a built-in validation library. The library is loaded using the following line:
$this->load->library('form_validation');
The CodeIgniter form validation library can perform some of the following actions:
- Check for required fields. It examines the submitted values and returns an error if a field tagged as required does not have a value.
- Data type validation โ some fields may require numeric values only. If a non-numeric value is detected, the library returns an error and aborts the form submission.
- Length validation โ some fields require a certain minimum or maximum number of characters. The validation library handles such cases.
- Data sanitization โ the library can remove malicious code from the submitted data for security. If the submitted values have active JavaScript or SQL injection code, the library strips the harmful code and renders it useless.
- Validate unique database fields โ suppose you have a sign-up form using an email address, and you want to ensure the address is unique. The library makes it easy to check the submitted data against a database table and field.
Validation rules are set using the following format:
$this->form_validation->set_rules('field','human readable field','rule',['custom message']);
Here:
- ‘field’ specifies the form field name to be validated by the library.
- ‘human readable field’ specifies the human-readable format of the field, displayed back to the user when an error occurs.
- ‘rule’ specifies the validation rule to be applied, such as required, numeric, or a minimum length.
- [‘custom message’] is optional and can set a custom validation message displayed when the rule fails.
The following is a CodeIgniter example for validating the contact number:
$this->form_validation->set_rules('contact_number', 'Contact Number', 'required');
Here:
- The code above checks if the field contact_number has been entered. If it is not set, it returns an error that says Contact Number field is required.
To run the validation against the set rules, we use the following function of the validation library:
$this->form_validation->run()
If the code above returns false, then one or more set rules have failed. If it returns true, then all validation rules have passed, and you may proceed with further action.
Let us look at more examples of validation rules. Suppose you want to validate several fields, such as the contact name, number, and email address. You can use the following code:
$rules = array( array( 'field' => 'contact_name', 'label' => 'Contact Name', 'rules' => 'required' ), array( 'field' => 'contact_number', 'label' => 'Contact Number', 'rules' => 'required', 'errors' => array( 'required' => 'You must provide a %s.', ), ), array( 'field' => 'email_address', 'label' => 'Email Address', 'rules' => 'required' ) ); $this->form_validation->set_rules($rules);
Here:
- In the example above, we provide an array of fields with rules for the set_rules function of the library. This makes it easier when you are validating several fields.
Unique Validation
If we want to validate the contact number to ensure we do not save the same number twice, we can use the following rule:
$this->form_validation->set_rules('contact_number', 'Contact Number','required|is_unique[contacts.contact_number]');
Here:
- | is used to pipe multiple rules together.
- is_unique[contacts.contact_number] checks if the value for contact_number is unique against the contact_number field values in the database table contacts.
Displaying Form Validation Error Messages
If an error occurs during the processing of the form, you can use the following code to display the validation errors:
<?php echo validation_errors(); ?>
Here:
- The function above returns all the errors that occurred.
Populating Submitted Form Data: Sticky Forms
Some forms have many fields, and if an error occurs, you want to make sure the data that was added correctly is preserved. The validation library has mechanisms for accomplishing that, using the following code:
<?php echo set_value('field_name'); ?>
Here:
- The code above displays the input that the user had entered.
For a complete reference guide on the methods available in the validation library, refer to the API documentation in the official CodeIgniter user guide: https://codeigniter.com/userguide3/libraries/form_validation.html.
CodeIgniter Form Validation Example
Throughout this tutorial series, we have been adding code to our tutorial project, a contacts management application. In this section, we will load the validation library and see how to put it to practical use in a real-world example. Modify the routes code as follows to include the store method:
$route['default_controller'] = 'welcome'; $route['contacts'] = 'contacts'; $route['create'] = 'contacts/create'; $route['store'] = 'contacts/store'; $route['edit/:id'] = 'contacts/edit'; $route['update/:id'] = 'contacts/update'; $route['delete/:id'] = 'contacts/delete'; $route['users'] = 'welcome/users';
Let us now load the form validation library in the Contacts controller and set some validation rules. Modify the code as shown below:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Contacts extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url', 'form'); $this->load->library('form_validation'); } public function index() { $this->load->view('header'); $this->load->view('contacts/index'); $this->load->view('footer'); } public function create() { $this->load->view('header'); $this->load->view('contacts/create'); $this->load->view('footer'); } public function store() { $rules = array( array( 'field' => 'contact_name', 'label' => 'Contact Name', 'rules' => 'required' ), array( 'field' => 'contact_number', 'label' => 'Contact Number', 'rules' => 'required', 'errors' => array( 'required' => 'You must provide a %s.', ), ), array( 'field' => 'email_address', 'label' => 'Email Address', 'rules' => 'required' ) ); $this->form_validation->set_rules($rules); if ($this->form_validation->run() == FALSE) { $this->load->view('header'); $this->load->view('contacts/create'); $this->load->view('footer'); } else { redirect(base_url('contacts')); } } public function edit($id) { $this->load->view('header'); $this->load->view('contacts/edit'); $this->load->view('footer'); } public function update($id) { $this->load->view('header'); $this->load->view('contacts/update'); $this->load->view('footer'); } public function delete($id) { $this->load->view('header'); $this->load->view('contacts/delete'); $this->load->view('footer'); } }
Here:
- $rules = array(โฆ) defines the validation rules.
- $this->form_validation->set_rules($rules); sets the validation rules.
- if ($this->form_validation->run() == FALSE) {โฆ} runs the validation rules, and if they fail the form is redisplayed with validation errors. If validation passes, we redirect to the list contacts page. Under normal circumstances we would write the data to the database, which we do in the next tutorial on databases.
Modify the create view in application/views/contacts/create.php as shown below:
<div class="column"> <h2 class="title">Create Contact</h2> <div class="notification is-danger"> <?php echo validation_errors(); ?> </div> <form action="<?= base_url('contacts/store') ?>" method="POST"> <div class="field"> <label class="label">Contact Name</label> <div class="control"> <input id="contact_name" name="contact_name" class="input" type="text" value="<?php echo set_value('contact_name'); ?>" placeholder="Type the contact name"> </div> </div> <div class="field"> <label class="label">Contact Number</label> <div class="control"> <input id="contact_number" name="contact_number" class="input" type="text" value="<?php echo set_value('contact_number'); ?>" placeholder="Type the contact number"> </div> </div> <div class="field"> <label class="label">Email Address</label> <div class="control"> <input id="email_address" name="email_address" class="input" type="email" value="<?php echo set_value('email_address'); ?>" placeholder="Type the email address"> </div> </div> <div class="field is-grouped"> <div class="control"> <button class="button is-link">Save Contact</button> </div> </div> </form> </div>
Here:
- <?php echo validation_errors(); ?> displays the errors that occur, if any, during the validation process.
- <?php echo set_value(‘contact_name’); ?> sets the value that was previously entered, if any.
Load the following URL into your web browser, then click on Create Contact without entering any values:


