Codeigniter 4 Form Validation Tutorial with Example

In this tutorial, we will be exploring how to perform form validation in a CodeIgniter 4 application. Validation is an essential aspect of web development to ensure that the data submitted by users is accurate, consistent, and secure. In CodeIgniter 4, you can use the form validation library to handle form validation on the server-side.

To get started, we will create a bootstrap form using HTML and CSS. Bootstrap is a popular framework that offers a range of pre-built CSS and JavaScript components, making it easier to design responsive and mobile-friendly interfaces.

Once we have our form, we will define the validation rules using the CodeIgniter 4 form validation library. The library offers a range of built-in rules that can be used to validate various form inputs, such as required fields, email addresses, and passwords. You can also define custom validation rules to meet your specific requirements.

In this example, we will demonstrate how to validate a form that collects user registration data, including the user’s name, email address, and password. We will ensure that all fields are required, the email address is valid, and the password meets minimum strength requirements.

After defining the validation rules, we will then process the form data and display any errors if validation fails. If the validation passes, we will save the data to a database or perform any other required actions.

In summary, this tutorial will guide you through the process of creating a bootstrap form and validating form data on the server-side in a CodeIgniter 4 application using the form validation library. By the end of this tutorial, you will have a solid understanding of how to handle form validation in CodeIgniter 4 and will be able to apply these concepts to your own web applications.

How to Validate Form Data in CodeIgniter 4 Apps

Follow the below steps and validate form data on server-side in CodeIgniter 4 framework:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Model and Controller
  • Create Views
  • Start Development server

Download Codeigniter Latest

To get started with CodeIgniter 4, the first step is to download the latest version of the framework. You can download the framework from the official CodeIgniter website at https://codeigniter.com/download.

Once you have downloaded the CodeIgniter 4 setup, unzip the archive and save it in your local system. You can save it in the XAMPP/htdocs/ directory if you are using XAMPP as your local development environment.

After unzipping the CodeIgniter 4 setup, you will see a folder with the name “CodeIgniter4-x.x.x” (x.x.x represents the version number). It is recommended to rename this folder to something more meaningful, like the name of your project. In this example, we will rename the folder to “demo”.

Renaming the folder will make it easier for you to identify your project and keep your files organized. It will also help you to avoid conflicts with other CodeIgniter 4 projects that you may have on your system.

In summary, to get started with CodeIgniter 4, you need to download the latest version of the framework from the official website, unzip the setup, and rename the folder to something meaningful. Once you have completed these steps, you can start building your application using CodeIgniter 4.

Basic Configurations

Now, we need to configure some basic settings in the “app/config/app.php” file. To do this, we will open the “config.php” file located in the “application/config” folder using a text editor.

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

Create Database With Table

Now, we need to create a database for our CodeIgniter 4 application. To do this, we will use PHPMyAdmin, which is a popular web-based database management tool.

To get started, open PHPMyAdmin and create a new database with the name “demo”. You can do this by selecting the “New” button from the left-hand menu and then entering the name “demo” in the appropriate field.

After you have created the database, you can use SQL queries to create tables and insert data. For example, if you want to create a table to store user registration data, you can use the following SQL query:

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;

Setup Database Credentials

Now, we need to connect our CodeIgniter 4 project to the database. To do this, we will open the “database.php” file located in the “app/Config” folder using a text editor.

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,
];

Create Model and Controller

Now, we need to create a model for our CodeIgniter 4 application. To do this, we will navigate to the “app/Models” folder and create a new file called “contactModel.php”.

Once you have created the file, you will need to add some code to define the functionality of the model. This code will allow your application to interact with the database and perform CRUD (Create, Read, Update, Delete) operations on the contact data.

<?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class ContactModel extends Model
{
    protected $table = 'contacts';
 
    protected $allowedFields = ['name', 'email', 'message'];
}

Create Controller

Now Go to app/Controllers and create a controller name Contact.php. In this controller, we will create some method/function. We will build some of the methods like :

  • Index() – This is used to display contact us form.
  • create() – This is used to validate form data server-side and store into mysql database.
<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
use App\Models\ContactModel;
 
class Contact extends Controller
{
    public function index()
    {    
         return view('contact');
    }
 
    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');
        }
    }
}

Create Views

Now we need to create contact.php, go to application/views/ folder and create contact.php file. and update the following HTML into your files:.

<!DOCTYPE html>
<html>
    <head>
        <title>Codeigniter 4 Form Validation Example - Torque Programming</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 - Torque Programming</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>

Start Development server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/contact

Conclusion

In this Codeigniter 4 Bootstrap form validation tutorial, We have successfully validated form data on the server-side. After successfully validate data on the server-side, we send it to users on the success page.

You May Also Like

  1. How to Install CodeIgniter 4 in Xampp
  2. Install / Download Codeigniter 4 By Manual, Composer, Git
  3. Codeigniter 4 Application Folder / Directory Structure
  4. React JS CRUD with CodeIgniter 4 and MySQL 8
  5. Send Email in CodeIgniter 4 With SMTP
  6. Codeigniter 4 Resize, Compress Image with Image Manipulation

Leave a Reply

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