CodeIgniter 4 Form Validation Example Tutorial

Apr 25, 2022 . Admin



Hi Dev,

In this post, we will learn form validation codeigniter 4 example. I would like to share with you codeigniter 4 form validation error message display. This article will give you simple example of form validation codeigniter 4 library. step by step explain codeigniter 4 form validation example.

  1. A View file containing a form.
  2. A View file containing a “success” message to be displayed upon successful submission.
  3. A controller method to receive and process the submitted data.

Let’s create those three things, using a member sign-up form as the example.

Step 1: Install Codeigniter 4

This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2: Basic Configurations

Next, we will set 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.

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table

In this section, we require to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

CREATE TABLE contacts (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    message varchar(250) NOT NULL COMMENT 'Message',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;
Step 4: Setup Database Credentials

In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];
Step 5: Create Model

So go to app/Models/ and create here one model. And you need to create one model name contactModel.php and update the following code into your contactModel.php file:

app/Models/ContactModel.php
<?php
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class ContactModel extends Model
{
    protected $table = 'contacts';
 
    protected $allowedFields = ['name', 'email', 'message'];
}
Step 6: Create Controller

In this section go to app/Controllers and create a controller name Contact.php. In this controller, we will create some method/function.

app/Controllers/Contact.php
<?php 
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\ContactModel;
 
class Contact extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
        return view('contact');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {  
 
    helper(['form', 'url']);
         
        $val = $this->validate([
            'name' => 'required',
            'email' => 'required',
            'message'  => 'required',
        ]);
 
        $model = new ContactModel();
 
        if (!$val)
        {
 
            echo view('contact', [
                   'validation' => $this->validator
            ]);
 
        }
        else
        { 
       
            $model->save([
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'message'  => $this->request->getVar('message'),
            ]);
 
            echo view('success');
        }
    }
}
Step 7: Create Views

Now we need to create contact.php, go to application/views/ folder and create contact.php file.

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter 4 Form Validation Tutorial - MyWebtuts.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <br>
        <?= \Config\Services::validation()->listErrors(); ?>
     
        <div class="row">
            <div class="col-md-9">
                <form action="<?php echo base_url('public/index.php/contact/create') ?>" method="post" accept-charset="utf-8">
         
                    <div class="form-group">
                        <label for="formGroupExampleInput">Name</label>
                        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
                     
                    </div> 
         
                    <div class="form-group">
                        <label for="email">Email Id</label>
                        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
                    </div>   
         
                    <div class="form-group">
                        <label for="message">Message</label>
                        <textarea name="message" class="form-control"></textarea>
                    </div>
         
                    <div class="form-group">
                        <button type="submit" id="send_form" class="btn btn-success">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

This below line display error messages on your web page:

<?= \Config\Services::validation()->listErrors(); ?>

Now we need to create success.php file, so go to application/views/ and create success.php file. And put the below code here.

<!DOCTYPE html>
<html>
<head>
    <title> Codeigniter 4 Form Success </title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center"> Thank You for contact us</h1>
    </div>
</body>
</html>
Step 8 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/

It will help you....

#Codeigniter 4