Monday, April 30, 2012

CodeIgniter's Form Validation w/ jQuery Ajax

In order to use CI's form validation you need to load the form_validation library, then you need to set rules on each field you want to validate, If validation is successful a $this->form_validation->run() should be equal to TRUE. Ajax can be used to avoid a full page refresh resulted from a form validation. 


A good example to this is a user registration page, suppose the page's username, password and confirm password fields are all required plus the confirm password field needs to match the password field value.


Please examine the controller class below:
<?php
 class Account extends CI_Controller{

  function __construct(){
   parent::__construct();
   $this->load->helper(array('form', 'url'));
   $this->load->library('form_validation');
  }
   
  function index() {
   $data['title'] = 'CI error validation using jQuery Ajax';
   $this->load->view('signup', $data);
  }

  function signup() {  
   $this->form_validation->set_rules('un', 'Username', 'trim|required');
   $this->form_validation->set_rules('pw', 'Password', 'trim|equired');
   $this->form_validation->set_rules('pw1', 'Password Confirmation', 'trim|required|matches[pw]');
   if ($this->form_validation->run() == FALSE) {
    echo validation_errors();
   } else {
    //TODO: Logic for user registration.
   }  
  }
 } ?>
**** An echo validation_errors(); is use to raise error messages on the page. This error messages will be pass asynchronously using an Ajax call.

Please examine the view page below:
<html>
    <head>
        <title><?= $title; ?></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>        
        <script type="text/javascript">
        $(document).ready(function(){
  $('#reg').click(function(){
   $.post("<?= base_url() . 'index.php/account/signup' ?>",
    $("form").serialize(),
    function(result) {
     $("#error_message").html(result).appendTo("form"); 
   },"html");
  });    
        });
        </script>
    </head>
    <body>
        <form>
        <div id="error_message" style="color:red"></div>
        <table>
  <caption>Sign Up Now</caption>
  <tr><td>Username</td>
   <td><?= form_input('un', ''); ?></td></tr>
  <tr><td>Password</td>
   <td><?= form_password('pw', ''); ?></td></tr>
  <tr><td>Confirm Password</td>
   <td><?= form_password('pw1', ''); ?></td></tr>
        </table>
        <div style="height: 20px"></div>
        <input type="button" id="reg" value="Register" />
        </form>
 </body>
</html>
**** On the $(document).ready function a click event is attached using $('#reg').click function, this event can trigger a jQuery post that will transfer a serialized values of form fields to the /account/signup action method, A callback function will later give the returned data using the result variable.


**** If an error occurred the result's value will be appended to the form element, refer below.

**** Using alert(result); The actual returned data is showed below.