CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
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.
Before using form validation, load the library in your controller:
$this->load->library('form_validation');
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>
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!"; } } }
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]');
You can add custom error messages:
$this->form_validation->set_rules( 'name', 'Name', 'required', array('required' => 'You must provide a %s.') );
Customize error message display:
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');