Codeigniter 4 Server Side Form Validation Tutorial Example

In this Codeigniter 4 form validation example, we will assist you how to implement server-side form validation in Codeigniter 4 app from scratch.

Codeigniter form validation tutorial; Codeigniter comes loaded with Form Helper; ideally, the primary role of Form Helper is to solve validation related problems.

Form validation deals with a technical process and checks the form values, and makes sure whether the information provided by the user is authentic or not.

Form helper helps you validate the form input values like name, email, phone number, password etc. On clicking on the submit button, forma validation does its job and display the error message to the user and let them know what they did wrong and fix it ASAP to proceed further.

You will be given bit by bit information on using form validation in Codeigniterthe 4 app, not just that we will also cover form validation with error alert messages.

How to Create Form and Implement Server Side Form Validation in Codeigniter 4

  • Step 1: Create Codeigniter App
  • Step 2: Establish Database Connection in Codeigniter
  • Step 3: Create Table in DB
  • Step 4: Setting Up Model File
  • Step 5: Setting Up Form Controller
  • Step 6: Register New Routes
  • Step 7: Create Form View File
  • Step 8: Run App in Browser

Create Codeigniter App

The initial step is about downloading a brand new Codeigniter app; you can do it with the given command.

Furthermore, you can install Codeigniter app manually from the website.

composer create-project codeigniter4/appstarter

Establish Database Connection

A further task is to establish Codeigniter and database connection; make sure to update the DB credentials in app/Config/Database.php.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        '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,
    ];

Create Table in DB

After validating the form, we have to store the user-provided values into the database. For that, you must have a table created in the DB for storing the values.

Ensure you run the given command from the PHPMyAdmin’s SQL console.

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  `mobile` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Setting Up Model File

Once the database and table have been created, next move on to the Models folder, create a modal file.

Define table name and the values into the app/Models/Contact.php file.

<?php 

namespace App\Models;

use CodeIgniter\Model;

class Contact extends Model
{

  protected $table = 'contacts';

    protected $allowedFields = [
      'name', 
      'email', 
      'mobile'
    ];

}

Controller Formation

The crucial role of the controller is to lay the foundation of business logic; for instance you have to define the index() and store methods in the app/Controllers/ContactController.php.

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

class ContactController extends Controller
{

    public function index() {
        helper(['form']);
        $data = [];
        return view('index');
    }
 
    public function store() {
        helper(['form']);
        $rules = [
            'name' => 'required|min_length[2]',
            'email' => 'required|valid_email',
            'mobile' => 'required|max_length[12]|numeric'
        ];
          
        if($this->validate($rules)){
            $contact = new Contact();

            $data = [
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'mobile'  => $this->request->getVar('mobile'),
            ];

            $contact->save($data);

            return redirect()->to('/contact');
        }else{
            $data['validation'] = $this->validator;
            echo view('index', $data);
        }        
    }

}

Register New Routes

Formation of new routes is essential; they process the controller logic and retrieve the response in the browser.

Go ahead define the routes simultaneously with GET and POST methods in the app/Config/Routes.php.

$routes->get('contact', 'ContactController::index');
$routes->match(['get', 'post'], 'ContactController/store', 'ContactController::store');

Create Form View File

Next, create the form’s view file by adding the following code to the app/Views/index.php file.

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

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter 4 Form Validation Integration Example</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
		.container {
			max-width: 500px
		}
	</style>
</head>

<body>
	<div class="container">
		<?php $validation = \Config\Services::validation(); ?>
		<form method="post" action="<?php echo base_url() ?>/ContactController/store">
			<div class="mb-3">
				<input type="text" name="name" class="form-control" placeholder="Name">

				<?php if($validation->getError('name')) {?>
				<div class='text-danger mt-1'>
					<?= $error = $validation->getError('name'); ?>
				</div>
				<?php }?>
			</div>


			<div class="mb-3">
				<input type="text" name="email" class="form-control" placeholder="Email">

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

			<div class="mb-3">
				<input type="text" name="mobile" class="form-control" placeholder="Mobile">

				<?php if($validation->getError('mobile')) {?>
				<div class='text-danger mt-1'>
					<?= $error = $validation->getError('mobile'); ?>
				</div>
				<?php }?>
			</div>

			<div class="d-grid">
				<button type="submit" class="btn btn-dark">Send</button>
			</div>
		</form>
	</div>
</body>

</html>

Run App in Browser

The view has been properly created and set up; now, you have to put less effort into the next task and run the command to view the app in the browser.

php spark serve
http://localhost:8080/contact

Codeigniter 4 Form Validation

Conclusion

If you are a novice developer and strived hard to understand how to get started with form validation in Codeigniter.

We can guarantee you this example of form validation in CodeIgniter will enlighten you towards the righteous path with the formal process of dealing with server-side form validation in Codeigniter.