How to Use Form Validation in Codeigniter

09 Mar 2023 | Codeigniter


In this tutorial, you will learn how to use form validation in codeigniter with example. Form validation is an essential component of any web application that accepts user input. CodeIgniter, a popular PHP framework, provides a built-in form validation library that simplifies the process of validating user input.

We will walk through the process of using form validation in CodeIgniter with an example, so if you don’t know how to use form validation in codeigniter just follow these simple steps.

Step 1: Create Routes

In the first step, we need to create a route to display the form and post the form inputs, so open and paste the following code into this file.

application\config\config.php

$route['default_controller'] = 'user';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['add-user'] = "user/store";

Step 2: Create Controller File

In this step, we need to create a user controller and methods first to display the form and second to validate the form input.

application\controllers\User.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		$this->load->view('user');
	}

	public function store()
	{
		$this->form_validation->set_rules('first_name', 'First Name', 'required');
		$this->form_validation->set_rules('last_name', 'Last Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('phone_number', 'Phone Number', 'required|numeric');
		$this->form_validation->set_rules('gender', 'Gender', 'required');

		if ($this->form_validation->run() == FALSE) {
			$this->load->view('user');
		}else{
			echo "Record added successfully";
		}
	}
}

Step 3: Load the Form Validation Library

The third step in using form validation in CodeIgniter is to load the form validation library. This is done by adding the following code to the controller:

	public function __construct()
	{
		parent::__construct();

		$this->load->library('form_validation');
	}

Step 4: Create View File

After loading the form validation library, the next step is to create a view file to display the form, so let's create it and make the following changes.

application\views\user.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>User</title>

    <style>
      label{
        font-weight: 500;
      }
    </style>

  </head>
  <body>


<section class="vh-100">
  <div class="container py-5 h-100">

<div class="row my-4">
  <div class="col-lg-2 mx-auto p-1" style="background-color: #1f386a;">
      <a href="https://www.buildwithphp.com/">
        <img src="https://www.buildwithphp.com/front/images/logo.webp" class="img-fluid">
      </a>
  </div>
</div>

    <div class="row justify-content-center align-items-center h-100">
      <div class="col-12 col-lg-9 col-xl-7">
        <div class="card shadow-2-strong card-registration rounded">
          <div class="card-body p-4 p-md-5">
            <h3 class="mb-4 pb-2 pb-md-0 mb-md-5 text-center">Codeigniter Form Validation Example</h3>

            <?php //echo validation_errors(); ?>

            <form method="post" action="add-user">

              <div class="row">
                <div class="col-md-6">

                  <div class="form-group">
                    <label class="form-label" for="firstName">First Name</label>
                    <input type="text" id="firstName" name="first_name" class="form-control <?= form_error('first_name')?'is-invalid':''; ?>" placeholder="Enter First Name" />
                    <?php if (form_error('first_name')): ?>
                      <span class="invalid-feedback" role="alert">
                        <strong><?= form_error('first_name'); ?></strong>
                      </span>
                    <?php endif ?>
                  </div>

                </div>
                <div class="col-md-6">

                  <div class="form-group">
                    <label class="form-label" for="lastName">Last Name</label>
                    <input type="text" id="lastName" name="last_name" class="form-control <?= form_error('last_name')?'is-invalid':''; ?>" placeholder="Enter Last Name" />
                    <?php if (form_error('last_name')): ?>
                      <span class="invalid-feedback" role="alert">
                        <strong><?= form_error('last_name'); ?></strong>
                      </span>
                    <?php endif ?>
                  </div>

                </div>
              </div>


              <div class="row">
                <div class="col-md-6">

                  <div class="form-group">
                    <label class="form-label" for="emailAddress">Email</label>
                    <input type="email" id="emailAddress" name="email" class="form-control <?= form_error('email')?'is-invalid':''; ?>" placeholder="Enter Email"/>
                    <?php if (form_error('email')): ?>
                      <span class="invalid-feedback" role="alert">
                        <strong><?= form_error('email'); ?></strong>
                      </span>
                    <?php endif ?>
                  </div>

                </div>
                <div class="col-md-6">

                  <div class="form-group">
                    <label class="form-label" for="phoneNumber">Phone Number</label>
                    <input type="tel" id="phoneNumber" name="phone_number" class="form-control <?= form_error('phone_number')?'is-invalid':''; ?>" placeholder="Enter Phone Number"/>
                    <?php if (form_error('phone_number')): ?>
                      <span class="invalid-feedback" role="alert">
                        <strong><?= form_error('phone_number'); ?></strong>
                      </span>
                    <?php endif ?>
                  </div>

                </div>
              </div>

              <div class="row">
                <div class="col-md-12">

                  <div class="form-group">
                    <label class="form-label" for="gender">Gender</label>
                    <select id="gender" name="gender" class="form-control <?= form_error('gender')?'is-invalid':''; ?>">
                      <option value="">Select Gender</option>
                      <option value="male">Male</option>
                      <option value="female">Female</option>
                    </select>
                    <?php if (form_error('gender')): ?>
                      <span class="invalid-feedback" role="alert">
                        <strong><?= form_error('gender'); ?></strong>
                      </span>
                    <?php endif ?>
                  </div>

                </div>
              </div>


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

            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>



    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>

Conclusion:

In this article, we have walked through the process of using form validation in CodeIgniter. By following these steps, you can ensure that your web application accepts valid user input and provides a better user experience. By implementing form validation in your CodeIgniter application.

Congratulations, Now the above code is ready to run.

Buddy! I hope you relished the tutorial, and it was good to see you again. Keep learning. Keep visiting.

Related Blogs