Codeigniter 4 Server Side Form Validation with Error Message Example

Apr 26, 2022 . Admin



Hi Guys

In this short tutorial we will cover a Codeigniter server side form validation with an error message example. I would like to share with you Codeigniter 4 form validation error message display. if you want to see an example of form validation Codeigniter 4 example then you are in the right place. I explained simply about the form validation Codeigniter 4 library. You just need to do some steps to do the Codeigniter 4 form validation example.

we can use default following validation rules of codeigniter. We can use default following validation rules of codeigniter.

  1. required
  2. regex_match
  3. matches
  4. differs
  5. is_unique
  6. min_length
  7. max_length
  8. exact_length
  9. greater_than

So here I gave you a full example of form validation in the Codeigniter application. I created a simple form with first name, last name, email, and Mobile Number like a contact us form and I set server side validation.

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

Here in this step, we will set some basic configuration on the config.php file, so let’s go to application/config/config.php and open this file on the text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';
Step:3 Create Database With Table

Here in this step, we need to create a database name demo, so let’s open your phpmyadmin and create the database with the name demo. you can use the below SQL query for creating a table in your database.

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    first_name varchar(100) NOT NULL COMMENT 'Name',
    last_name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
Step:4 Setup Database Credentials

Here in this step, we need in this step connect our project to the database. go to the application/config/ and open the database.php file in a text editor. We need to setup a database credential in this file like below.

$db['default'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);
Step:5 Create Controller

After then, we create a controller name Users.php. In this controller, we will create some method/function. We will build some of the methods like :-

  1. Index() – This is used to display a form.
  2. post_validate() – This is used to validate data on server side and store a data into database.
<?php
class Users extends CI_Controller {
  
    /**
      * Write code on Method
      *
      * @return response()
    */
    public function __construct()
    {
        parent::__construct();
        $this->load->library(array('form_validation','session'));
        $this->load->helper(array('url','html','form'));
        $this->load->database();
    }

    /**
      * Write code on Method
      *
      * @return response()
    */
    public function index()
    {
        $this->load->view('form_validation');
    }

    /**
      * Write code on Method
      *
      * @return response()
    */
    public function post_validate()
    {
 
        $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('contact_no', 'Contact No', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');
 
        $this->form_validation->set_error_delimiters('<div class="error">','</div>');
        $this->form_validation->set_message('required', 'Enter %s');
 
        if ($this->form_validation->run() === FALSE)
        {  
            $this->load->view('form_validation');
        }
        else
        {   
          $data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name' => $this->input->post('last_name'),
                'contact_no' => $this->input->post('contact_no'),
                'email' => $this->input->post('email'),
           );
   
            $insert = $this->db->insert('users', $data);
            
            if ($insert) {
                $this->load->view('success');
            } else {
                redirect( base_url('users') ); 
            }
        }
    }
}
Step:6 Create Views

Now in this step we will create a form_validation.php, go to the application/views/folder and create the form_validation.php file. Here put the below html code for showing the form.

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Form Validation - 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>
        <div class="row">
            <div class="col-md-9">
                <form action="<?php echo base_url('users/post_validate') ?>" method="post" accept-charset="utf-8">
                    <div class="form-group">
                        <label for="formGroupExampleInput">First Name</label>
                        <input type="text" name="first_name" class="form-control" id="formGroupExampleInput" placeholder="Please enter first name">
                        <?php echo form_error('first_name'); ?> 
                    </div> 
 
                    <div class="form-group">
                        <label for="formGroupExampleInput">Last Name</label>
                        <input type="text" name="last_name" class="form-control" id="formGroupExampleInput" placeholder="Please enter last name">
                        <?php echo form_error('last_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">
                        <?php echo form_error('email'); ?> 
                    </div>
 
                    <div class="form-group">
                        <label for="mobile_number">Mobile Number</label>
                        <input type="text" name="contact_no" class="form-control" id="contact_no" placeholder="Please enter mobile number" maxlength="10">
                        <?php echo form_error('contact_no'); ?> 
                    </div>
 
                    <div class="form-group">
                        <button type="submit" id="send_form" class="btn btn-success">Submit</button>
                     </div>
                </form>
            </div>
            <div class="col-md-3">
                <?php $this->load->view('layout/media_left_side_bar'); ?>
            </div>
        </div>
    </div>
</body>
</html>
Step:7 Success Views

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

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Form Validation - Mywebtuts.com </title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1> Thank You for Registered</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/

I hope it can help you...

#Codeigniter 4