CodeIgniter 4 Form Validation Example

In this tutorial I am going to show you how to validate form in CodeIgniter 4 framework. CodeIgniter 4 is a PHP based web framework makes your life easier to build the web application quickly right from the scratch. CodeIgniter 4 is still under development and it is supposed to be supported with PHP version 7.2+. I will also tell you how to retain the input values on form so that next time end users do not need to input the same values.

Validation is important thing in the world of web application to avoid any kind of security vulnerabilities or other issues with the data integrity. For example you won’t want to store integer value in the name field. For example you won’t want users to execute any kind of script that exploits your application.

So let’s start with the ideal scenario of validating a form in CodeIgniter framework:

  • A form is displayed to the end user
  • A user fills it and submit the form
  • If the user submit the form with incorrect data or missed the required field then the form is redisplayed with validation errors
  • This process continues until end users correct all validation errors

Let’s move on to implementation part how CodeIgniter form validation works.

Prerequisites

PHP 7.4.3, CodeIgniter 4.0.4

Project Directory

It’s assumed that you have setup PHP and CodeIgniter in Windows system.

Now I will create a project root directory called codeigniter-4-form-validation.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

Form or View File

This is view file that contains form. You can use CodeIgniter’s form_open() function to create a form or standard HTML form to build your form. The advantage of using the form_open() function is it automatically adds the action to the form. The below form is created in a file form.php under app/Views folder.

<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter 4 Form Validation Example</title>
</head>
<body>

	<div style="width: 600px; margin: auto;">
		<?php
			if(isset($errors)):
		?>
			<ul style="list-style: none; color: red;">
				<?php foreach ($errors as $error) : ?>
				<li><?= esc($error) ?></li>
				<?php endforeach ?>
			</ul>
		<?php
			endif;
		?>
		
		<?php
			if(isset($success)):
		?>
			<ul style="list-style: none; color: green;">
				<li><?= esc($success) ?></li>
			</ul>
		<?php
			endif;
		?>

		<?= form_open('form') ?>

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

			<h5>Password</h5>
			<input type="password" name="password" value="" size="50" />

			<h5>Password Confirm</h5>
			<input type="password" name="passconf" value="" size="50" />

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

			<p/>
			<div><input type="submit" name="submit" value="Submit" /></div>

		</form>
	</div>

</body>
</html>

In the above code I checked whether errors are there or not. If errors are there then iterated through them to display one by one in a list. I have applied inline style to appear the error texts in red color. The $errors variable is coming from the controller class.

Similarly I did for the success message to be displayed in green color. The $success variable is coming from the controller class.

I have added few fields which will be validated in controller class. The function set_value() is used to retain the entered value when the form is submitted otherwise field’s value will be cleared on form submit. If you want you can only retain values on form validation errors.

Controller Class

In the controller class I have loaded the required helper and validation classes. The following code is written into the file Form.php under app/Controllers folder.

<?php

/**
* Author: https://roytuts.com
*/

namespace App\Controllers;

class Form extends BaseController {
	
	public function index() {
        helper(['form', 'url']);

		if($this->request->getPost('submit')) {
			$validation =  \Config\Services::validation();
			
			$validation->setRules([
				'username' => ['label' => 'Username', 'rules' => 'required|min_length[5]|max_length[30]'],
				'password' => ['label' => 'Password', 'rules' => 'required|min_length[10]|max_length[20]'],
				'passconf' => ['label' => 'Password Confirm', 'rules' => 'required|min_length[10]|max_length[20]|matches[password]'],
				'email' => ['label' => 'Email Address', 'rules' => 'required|valid_email|max_length[150]']
			]);
			
			if (!$validation->withRequest($this->request)->run()) {
				echo view('form', ['errors' => $validation->getErrors()]);
			} else {
				echo view('form', ['success' => 'Validation for fields successfully passed!']);
			}
		} else {
			echo view('form');
		}
    }
	
}

In the above class I have loaded form and url helpers. When form has been submitted then only I am loading the validation class. I have set rules for each field. Each field is mandatory. Both password values must match. Email should be a valid email address. I have also specified minimum length and maximum length for all fields. You can also use other validations for each of the fields.

Then I execute the validation on the request using the withRequest($this->request)->run() function. If any error occurs then I am passing error into the errors variable otherwise I am passing success message on success variable which will be used on view file to display them.

On index() function call the form is displayed to end users. So I am not passing any data and simply loading the view form.php using view() function.

Route Config

You need to change the default controller in the app/Routes/Route.php file as Form is the default controller instead of Home.

You need to change as $routes->setDefaultController('Form'); and $routes->get('/', 'Form::index');.

Testing the Application

You can access the application via CLI interface by executing the command php spark serve on the project’s root directory from the command line tool.

Now access the application in the browser via URL http://localhost:8080. The home page displayed as shown below in the image:

codeigniter 4 form validation

If you do not enter any input value then you will see the error messages. You can also see other validation errors according to the rule set to each field when you enter incorrect values.

codeigniter 4 form validation

On validation success when you input all data correctly, you will see success message. Note that I have not retained input values for password fields.

validate form in codeigniter 4

That’s all about form validation in CodeIgniter 4. You might want to explore more features in validation then read in CodeIgniter documentation.

Source Code

Download

2 thoughts on “CodeIgniter 4 Form Validation Example

  1. Hi,
    I test it.

    But if I don’t need an email and set up validation without “required”, it reports me the error “The Email Address field must contain a valid email address.”, if the email is not entered.

    Please, what should I do with it?

    Thanks

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *