Form Validation in CodeIgniter 3 (Step-by-Step Example)
Form validation is one of the most essential parts of any web application, ensuring that submitted user data is clean, accurate, and secure. In this tutorial, you will learn how to perform form validation in CodeIgniter 3 using MySQL with step-by-step examples. We will create a simple registration form in CodeIgniter 3 as an example and apply CodeIgniter 3 validation rules, and store the validated data in a MySQL database.
Create a MySQL table for candidate details
Let us create the table named 'candidates' in MySQL database. Table structure is given below:
Table: candidates
This table stores details of all registered candidates.
Below are the columns in this table.
candidate_id - It is the primary key and auto incremented id of the candidate
name - Name of the candidate
address - Address of the candidate
email_id - Email Id of the candidate
age - Age of the candidate
Create table script for this table is given below.
candidates.sql
CREATE TABLE `candidates` (
`candidate_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`address` varchar(200) NOT NULL,
`email_id` varchar(100) NOT NULL,
`age` smallint(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `candidates`
ADD PRIMARY KEY (`candidate_id`);
ALTER TABLE `candidates`
MODIFY `candidate_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
After you create the table, verify if the table structure is the same as above.
Create the view for registration form (register.php)
It is a simple registration form with input fields name, address, email id and age. We will validate this form using CodeIgniter 3. For age validation, we will use a range (18-40) so that we can show how to use custom validation in CodeIgniter 3. Let us see the form below:
application/views/register.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Candidate Registration</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url('assets/css/style.css') ?>">
</head>
<body>
<div class="container">
<h4>Candidate Registration</h4>
<p class="error "><?php if ($err_msg != "") { echo $err_msg;}?></p>
<p class="success"><?php if ($succ_msg !="") {echo $succ_msg;}?></p>
<form id ="frm" action = "<?php echo base_url()?>register" method = "post">
<div class="form-group col-md-12">
<label>Name</label>
<input type = "text" name="name" id = "name" class="form-control" value="<?php echo set_value('name');?>" maxlength="100" placeholder="Enter Your Name">
<div class="error"><?php echo form_error('name'); ?></div>
</div>
<div class="form-group col-md-12">
<label>Address</label>
<textarea name="addr" id = "addr" class="form-control" maxlength="200" placeholder="Enter Your Address" ><?php echo set_value('addr');?></textarea>
<div class="error"><?php echo form_error('addr'); ?></div>
</div>
<div class="form-group col-md-12">
<label>Email Id</label>
<input type = "text" name="email" id = "email" class="form-control" value="<?php echo set_value('email');?>" maxlength="100" placeholder="Enter Your Email">
<div class="error"><?php echo form_error('email'); ?></div>
</div>
<div class="form-group col-md-12">
<label>Age <small>(Must be between 18 and 40 only)</small></label>
<input type = "number" name="age" id = "age" class="form-control" value="<?php echo set_value('age');?>" placeholder="Enter Your Age in Years">
<div class="error"><?php echo form_error('age'); ?></div>
</div>
<div class="col-md-12 text-center">
<input type ="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
</form>
</div>
</body>
</html>
This is a simple form with a few input fields and a submit button. Note that for each input field set_value() will repopulate the value in case of validation error for the field. Also, for each input field, a validation error message is displayed using form_error().
Write Controller with validation rules (CandidateController.php)
Our controller will have an index() method to display the form and a register() method to process the submitted form. register() method is the one where form validation will take place. We will have an additional method for the custom age validation using a callback function. Let's see the code below for the controller class.
application/controllers/CandidateController.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class CandidateController extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/
* @see https://codeigniter.com/user_guide/general/urls.html
*/
function __construct() {
parent::__construct();
$this->load->model('ModelCandidate');
}
public function index(){
$element = [];
$element['succ_msg'] = "";
$element['err_msg'] = "";
$this->load->view('register',$element);
}
public function register(){
$element = [];
$element['succ_msg'] = "";
$element['err_msg'] = "";
// validate each field
$this->form_validation->set_rules('name', 'Name', 'trim|required',
array(
'required'=>'You must provide a %s')
);
$this->form_validation->set_rules('addr', 'Address', 'trim|required',
array(
'required'=>'You must provide an %s')
);
$this->form_validation->set_rules('email', 'Email Id', 'trim|required|valid_email|is_unique[candidates.email_id]',
array(
'required'=>'You must provide an %s',
'valid_email' => 'This is not a valid email address',
'is_unique' => 'This %s already exists')
);
$this->form_validation->set_rules('age', 'Age', 'trim|required|callback_age_check',
array(
'required' => 'You must provide %s')
);
if ($this->form_validation->run() == FALSE) {
// validation not passed, so load the form again
$this->load->view('register',$element);
}
else {
// validation is success, so go for registration
// get the values of form fields
$name = $this->input->post('name');
$addr = $this->input->post('addr');
$email = $this->input->post('email');
$age = $this->input->post('age');
$data = array('name'=>$name, 'address'=>$addr, 'email_id'=>$email, 'age'=>$age);
$result = $this->ModelCandidate->register($data);
if ($result){
$element['succ_msg'] = "Registration successful";
}
else{
$element['err_msg'] = "Error in Registration";
}
$this->load->view('register',$element);
}
} // end of register method
public function age_check($age){
if (!empty($age)){
if ($age <18 || $age >40) {
$this->form_validation->set_message('age_check', '{field} must be between 18 and 40');
return false;
}
else
return true;
}
}
} // end of controller class
In the constructor, we are loading the model named 'ModelCandidate'.
Controller Method index()
index() method is executed by default in a controller. In this method, it just loads the view that displays the registration form.
Controller Method register()
This method gets executed after form submission. It writes validation rules for each field. If validation fails for a field, it reloads the view with an error message displayed for the field. But if all fields are validated successfully, this method calls a Model method to insert a row in the database.
It uses form_validation->set_rules() method for each field. Validation for the Age field is done using a custom callback method named age_check() which is defined later in the controller. This callback method returns TRUE or FALSE. Let's see the callback method age_check() below:
public function age_check($age){
if (!empty($age)){
if ($age <18 || $age >40) {
$this->form_validation->set_message('age_check', '{field} must be between 18 and 40');
return false;
}
else
return true;
}
}
It takes the value of the field as a parameter and checks if the value is between 18 and 40. If the value is outside this range, it sets a message and returns FALSE. Otherwise, it returns TRUE.
The Model (ModelCandidate.php)
In the model, register() method takes the input array and uses $db->insert() to insert a row in the database table. Below is the model code:
application/models/ModelCandidate.php
class ModelCandidate extends CI_Model {
function __construct() {
parent::__construct();
}
function register($data = []) {
if (!empty($data)) {
$result = $this->db->insert('candidates', $data);
return $result;
}
}
}
We added a few simple styles here, you can always add better styles.
Update Configuration files and Test the Application
Let us now update a few setup files before we run the application. The project folder name is 'registration' under xampp/htdocs. So, the root directory is xampp/htdocs/registration.
The folder 'assets' is created for the custom stylesheet.
We will update few files in config folder and also write .htaccess file under the root. See below:
Run localhost/registration in the browser. You will see the registration form displayed as below:
Test is all validations are working. Just try to submit an incomplete form and see the error messages. Do not forget to test age validation.
When you enter all valid values and submit the form, registration should be completed successfully.
Conclusion
In this tutorial, you learned how to apply CodeIgniter form validation rules, handle input errors, and securely store data into a MySQL database. We also learned how to use custom validation in CodeIgniter 3. With this, you can ensure that only valid and properly formatted data enters your system.
Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.
Post a Comment