In this section, We'll go through the basic form validation concepts in CodeIgniter Framework.
In order to implement form validation you'll need three things:
- A View file containing a form.
- A View file containing a "success" message to be displayed upon successful submission.
- A controller method to receive and process the submitted data.
Using a text editor, create a controller called Form.php. In it, place this code and save it to your application/controllers/
directory:
<?php
class Form extends CI_Controller {
public function index() {
/* Load form helper */
$this->load->helper(array('form'));
/* Load form validation library */
$this->load->library('form_validation');
/* Validation rule */
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('form');
}
else {
$success = "Submit successfully!";
$this->load->view('form', compact('success'));
}
}
}
?>
Using a text editor, create a form called form.php. In it, place this code and save it to your application/views/
directory:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-2"></div>
<div class="col-md-8" style="margin-top:20px">
<?php
echo form_open('form/index');
echo validation_errors();
if (isset($success))
echo '<p>'.$success.'</p>';
?>
<div class="form-group">
<label for="email">Name:</label>
<input type="text" id="name" name="name" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" id="email" name="email" />
</div>
<div class="form-group">
<label for="email">Password:</label>
<input type="password" id="password" name="password" />
</div>
<button type="submit" class="btn btn-success">Submit</button>
<?php
echo form_close();
?>
</div>
<div class="col-md-2"></div>
</body>
</html>
To try your form, visit your site using a URL similar to this one:
http://localhost/codeigniter/index.php/form/index
It will produce the following screen: