In this article, We will learn how to validate a form in Codeigniter 3. Load the URL and form helper with the form_validation library, then validate the form.
use the following steps to validate the form:
Step 1: Make HTML Form
create a view and put the following code to make form.
application/views/home.php
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action = "<?php echo base_url(); ?>Home/save" method = "post">
<?php echo validation_errors(); ?>
<h5>Form validation</h5>
<input type = "text" name ="name" value ="" placeholder="Name"/><br><br>
<input type = "text" name ="email" value ="" placeholder="Email"/><br> <br>
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>
</html>
Step 2: Make Controller
make controller to get the html form data from view
application/controllers/Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
}
public function index() {
$this->load->view('home');
}
public function save() {
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE) {
$this->load->view('home');
} else {
//if form successfully validated
//store data in db
}
}
}
I hope it will work for you ...........