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 function to receive and process the submitted data.
The Form
Using a text editor, create a form called myform.php. In it, place this code and save it to your applications/views/ folder:
<html> <head> <title>My Form</title> </head> <body> <?php echo validation_errors(); ?> <?php echo form_open('form'); ?> <h5>Username</h5> <input type="text" name="username" value="" size="50" /> <h5>Password</h5> <input type="text" name="password" value="" size="50" /> <h5>Password Confirm</h5> <input type="text" name="passconf" value="" size="50" /> <h5>Email Address</h5> <input type="text" name="email" value="" size="50" /> <div><input type="submit" value="Submit" /></div> </form> </body> </html>
The Success Page
Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your applications/views/ folder:
<html> <head> <title>My Form</title> </head> <body> <h3>Your form was successfully submitted!</h3> <p><?php echo anchor('form', 'Try it again!'); ?></p> </body> </html>
The Controller
Using a text editor, create a controller called form.php. In it, place this code and save it to your applications/controllers/ folder:
<?php class Form extends CI_Controller { function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } ?>
Just try it!!