Skip to content

Php CodeIgniter Server Side Form Validation Example

Last updated on April 7, 2015

Today we are going to learn more about server side validation using php codeigniter framework.Follow the below steps to do the server side validations.

Server side validation is most secure way than client side validation, because client side validation can be bypass through script manipulation tools. Below example is simple user login form, We are going to validate the User Name and Password fields using CodeIgniter’s validation library.

set_rules() method is used to define the validation rules for the form fields. $this->form_validation->run() return Boolean value, TRUE on success and FALSE on failure.

Create Codeigniter Controller Class called – Home.php

class Home extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->library(array('form_validation','session')); // load form lidation libaray & session library
		$this->load->helper(array('url','html','form'));  // load url,html,form helpers optional
	}	

	public function index(){
	
		// set validation rules
		$this->form_validation->set_rules('name', 'Name', 'required|min_length[4]|max_length[10]');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('number', 'Phone Number', 'required|numeric|max_length[15]');
		$this->form_validation->set_rules('subject', 'Subject', 'required|max_length[10]|alpha');
		$this->form_validation->set_rules('message', 'Message', 'required|min_length[12]|max_length[100]');

	
		// hold error messages in div
		$this->form_validation->set_error_delimiters('
', '
'); // check for validation if ($this->form_validation->run() == FALSE) { $this->load->view('form_validation_demo'); }else{ $this->session->set_flashdata('item', 'form submitted successfully'); redirect(current_url()); } } }

Create a view Page called form_validation_demo.php

This is the default page of the application. Here we are going to validate the userform.



session->flashdata('item')) { ?>
session->flashdata('item'); ?>
"form-control","name" => "name", "placeholder"=>"Enter Name","value" => set_value('name'))); ?>
"form-control","name" => "email", "placeholder"=>"Enter email","value" => set_value('email'))); ?>
"form-control","name" => "number", "placeholder"=>"Enter Phone Number","value" => set_value('number'))); ?>
"form-control","name" => "subject", "placeholder"=>"Enter Subject","value" => set_value('subject'))); ?>
"form-control","name" => "message", "placeholder"=>"Enter Message","value" => set_value('message'))); ?>

Finished 🙂

Hope this Tutorial is helpful to you, Please provide your comments if there is any issues.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments