Codeigniter 4 Form Validation Example Tutorial

Form validation in codeIgniter 4. In this example tutorial, i will guide you in detail on how to add validation rules with forms in Codeigniter 4 apps.

Note that, the validation happens on both sides like server-side and client-side, But in this example, I will explain to you about server side validation in codeigniter 4 apps using built-in codeigniter 4 validation rules.

When you use this codeigniter 4 form. then the following things will be:

  • When the user will fill the data in this form and submit it. So if all field pass codeigniter 4 validation rules. So the form data will be stored in the database.
  • When user will submit this form empty. Or the form will not fill any field and submit. Then the user will be redirected automatically to the form and it will show that validation error.

Codeigniter 4 Form Validation Example

You can learn by following the steps given below on how to add validate in form in CodeIgniter 4 apps:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Model and Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
	];

Step 5 – Create Model and Controller

Create FormModel.php file, so visit app/Models/ directory and create FormModel.php file. Then add the following code into your FormModel.php file:

<?php 
namespace App\Models;
use CodeIgniter\Model;

class FormModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'phone'];
}

Create FormController.php file. So, visit app/Controllers directory and create FormController.php.Then add the following code into it:

<?php 
namespace App\Controllers;
use App\Models\FormModel;
use CodeIgniter\Controller;

class FormController extends Controller
{

    public function create() {
        return view('contact_form');
    }
 
    public function formValidation() {
        helper(['form', 'url']);
        
        $input = $this->validate([
            'name' => 'required|min_length[3]',
            'email' => 'required|valid_email',
            'phone' => 'required|numeric|max_length[10]'
        ]);

        $formModel = new FormModel();
 
        if (!$input) {
            echo view('contact_form', [
                'validation' => $this->validator
            ]);
        } else {
            $formModel->save([
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'phone'  => $this->request->getVar('phone'),
            ]);          

            return $this->response->redirect(site_url('/submit-form'));
        }
    }

}

The index() function renders the contact form template into the view.

The contactForm() method handles the form of validation and contains various variables.

Step 6 – Create Views

Create contact_form.php view file, so visit application/views/ directory and create contact_form.php file. Then add the following HTML into contact_form.php file:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 Form Validation Example - Laratutorials.com</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 550px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
         
    <?php $validation = \Config\Services::validation(); ?>

    <form method="post" action="<?php echo base_url('/submit-form') ?>">
      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('name')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('name'); ?>
            </div>
        <?php }?>
      </div>
       

      <div class="form-group">
        <label>Email</label>
        <input type="text" name="email" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('email')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('email'); ?>
            </div>
        <?php }?>
      </div>

      <div class="form-group">
        <label>Phone</label>
        <input type="text" name="phone" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('phone')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('phone'); ?>
            </div>
        <?php }?>
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Submit</button>
      </div>
    </form>

  </div>
</body>

</html>

This below line display error messages on your web page:

        <?php if($validation->getError('email')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('email'); ?>
            </div>
        <?php }?>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->get('contact-form', 'FormController::create');
$routes->post('submit-form', 'FormController::formValidation');

Note that, the routes will be displaying the contact form and submitting the data in the database on successful form submission.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/contact-form

OR

http://localhost:8080/index.php/contact-form

Conclusion

Codeigniter 4 Form Validation tutorial with an example. In this tutorial, you have seen how to addform validation in the Codeigniter 4 application from scratch.

Recommende CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4

Leave a Comment