Advertisement
Google Ad Slot: content-top
CodeIgniter Form Validation
Form validation is an essential part of any web application. It ensures that the data entered by users is correct, safe, and secure before saving it to the database.
CodeIgniter provides a powerful Form Validation Library that makes it easy to validate form inputs with simple rules.
🔹 Step 1: Load the Form Validation Library
Before using form validation, load the library in your controller:
$this->load->library('form_validation');
🔹 Step 2: Create a Simple HTML Form
Create a file application/views/form_view.php:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation in CodeIgniter</title>
</head>
<body>
<h2>User Registration</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('FormController/register'); ?>
<p>
Name: <input type="text" name="name" value="<?php echo set_value('name'); ?>">
</p>
<p>
Email: <input type="text" name="email" value="<?php echo set_value('email'); ?>">
</p>
<p>
Password: <input type="password" name="password">
</p>
<p>
<input type="submit" value="Register">
</p>
</form>
</body>
</html>
🔹 Step 3: Create Controller for Validation
Create application/controllers/FormController.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class FormController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$this->load->view('form_view');
}
public function register() {
// Validation rules
$this->form_validation->set_rules('name', 'Name', 'required|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
if ($this->form_validation->run() == FALSE) {
// Reload form with error messages
$this->load->view('form_view');
} else {
// Success message
echo "Form Submitted Successfully!";
}
}
}
🔹 Step 4: Commonly Used Validation Rules
required→ Field must not be emptyvalid_email→ Valid email formatmin_length[n]→ Minimum number of charactersmax_length[n]→ Maximum number of charactersnumeric→ Only numbers allowedalpha→ Only alphabets allowedalpha_numeric→ Alphabets + Numbersmatches[field]→ Field must match another (e.g., confirm password)
Example:
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
🔹 Step 5: Custom Error Messages
You can add custom error messages:
$this->form_validation->set_rules(
'name', 'Name',
'required',
array('required' => 'You must provide a %s.')
);
🔹 Step 6: Set Delimiters for Error Messages
Customize error message display:
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');