Hi all, in this new post I want to teach you simple but effective way to make form validation easier.
Normally(like I was before), when we want to make our site more interactive, we make validation in client side to inform our user if the form already valid on the fly without waiting for data to be sent to server. But do you also do validation in server side too? Just in case user disabled the javascript?
If yes, then you make 2 validation both in client side and also in server side. Somehow, it’s not effective and wasting time right? Not to mention when something bad happen like client side and server side library give you different result hahaha (I experienced that kind of situation before 😀 ) .
Okay I understand … so in this tutorial, I want to explain some trick which maybe will make your life easier. I’ll using PHP with Codeigniter 3.0 as “Server side” example, you can use another framework or even another language if you want, because what I want tell here not the PHP but the approach. For client side, I’ll using plain HTML, AJAX call using jQuery, and Twitter Bootstrap as cosmetic.
The Controller
To make form call, we need at least have 2 page(you can use only one, but I never recommend doing that). 1st page is the form, and 2nd one is the form processor.
Okay, if you’re using CI, then you need make a controller with 2 method.
<?php /** * @property CI_Loader $load * @property CI_Form_validation $form_validation */ class Tutorial extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('form_validation'); $this->load->helper(array( 'form', 'url' )); } function index() { } function form_submit() { } }
As you can see in constructor I loaded 2 helpers and 1 library:
Form and URL helper also Form validation
Now make the view for the form, you can just copy paste the code 🙂 (warning for non CI user, please change some function like base_url() and form_open().
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Tutorial view</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script src="<?php echo base_url() ?>assest/script.js"></script> </head> <body> <div class="container"> <?php echo form_open('tutorial/form_submit', array('id'=>'form-data')) ?> <div class="form-group"> <label>Email address</label> <input type="text" name="email" class="form-control" placeholder="Please enter your email address"> </div> <div class="form-group"> <label>Name</label> <input type="text" name="name" class="form-control" placeholder="Please enter your name"> </div> <div class="form-group"> <label>Your age</label> <input type="text" name="age" class="form-control" placeholder="Please enter your age(must be a number more than 10)"> </div> <button class="btn btn-primary btn-submit" type="submit" disabled>Save data</button> <?php echo form_close(); ?> </div> </body> </html>
Please note, I put “disabled” attribute in the submit button to prevent user submit the form before all HTML DOM and action binding script in javascript executed. Once all DOM and action binding script is executed, The button will be enabled(see the js file content bellow).
Save the view as php file(i.e tutorial.php), and load the view via controller in “index” method.
function index() { $this->load->view('tutorial'); }
Okay, now open your browser, point your browser to http://where-your-ci-located/index.php/tutorial/ And you’ll find some simple form with 3 input:
- Email Address, we will make it must in valid email format and required.
- Name, we will make it required.
- Age, must numeric and equal or greater than 10 years old.
Ok now create the js files as you can see in view file, I put in “asset/script.js”.
$(function(){ // Place the form object in variable to make easier to use latter var theForm = $('#form-data'); /* now we bind action when form submitted */ theForm.submit(function(){ //make sure the page notredirected when submit action is executed return false; }); /* Enabling submit button. * You can prevent user submit form before all HTML DOM * loaded, which can result the page redirected and only shown an JSON * in your browser screen. */ $('.btn-submit').prop('disabled',false); });
Ok, first there are 3 part on js file above:
- I put form object in variable, to make easier to use in code(also make it more readable).
- I put action binding for submit action, and prevent default action for submitting form(redirect to action directive in form tag).
- I put for enabling the submit button, so user now can submit the form.
Ok now the fun part, we will add some codes in our JS file for AJAX calling and process it’s return. So please put the code bellow inside “theForm.submit(function(){ … })”
/* run AJAX call */ $.post( theForm.attr('action'), theForm.serialize(), function(json){ if ( json.st === false ){ /* when validation failed */ } else { /* when validation success */ } },'json');
To use AJAX Call from jquery, you need to call “$.post()” and you need to put 4 parameter:
- Target URL: here I get the value from form “action” parameter using “attr()” method.
- Data to be send to server
- Callback function
- data type : json, html, text, etc
In this case I’ll using JSON data type because it’s easier to use 🙂
Ok now back to our controller, now we must put some validation code in server side to validate our form input. We will place it in “form_submit” method in our controller.
function form_submit() { $this->form_validation->set_rules('email', 'Email', 'valid_email|trim|required') ->set_rules('name', 'Name', 'trim|required') ->set_rules('age', 'Age', 'trim|required|numeric|greater_than_equal_to[10]'); if ( $this->form_validation->run() === FALSE ) { /* validation vailed, return status to FALSE and return the error message */ echo json_encode(array( 'st' => FALSE, 'msg'=> validation_errors() )); } else { /* validation is success, * add more code here like processing data, database insert, etc */ echo json_encode(array('st'=>TRUE)); } exit; }
I hope you understand how to use Codeigniter form validation, it’s just simply tell the class to validate “[field-name]” and set the “[label-for-the-field]” and set the “[rules]”.
Then after that, you can run the validator which will return either TRUE or FALSE. If validator run FALSE, you can get the error message using “validation_error()” function.
Ok back to code, when validation is fail, we will return JSON encoded string with 2 index, first is “st” (status) which return either TRUE or FALSE and the 2nd one is the error messages. But when validation goes well, you can only return “st” which set to TRUE.
Ok, let’s see if it’s works. Open the browser and open the form, If you’re using Firefox like me, you may need “firebug” extension to trace/debug javascript AJAX call, or you can use chrome developer tools if you prefer using Chrome.



Ok, as you see, our codes works very nicely, but how we can show the error message to user? Don’t worry, we’re not finished yet.
We will using Twitter Bootstrap Javascript Alert Plugin to make it bit “looks good”, but before that, we need to add “container” where we will put those message. So make one, and place it on top of form tag.
<div id="msg-container"></div>
Now back to javascript file, and add several line in “if/else” statement of AJAX post result:
/* now we bind action when form submitted */ theForm.submit(function(){ /* run AJAX call */ $.post( theForm.attr('action'), theForm.serialize(), function(json){ if ( json.st === false ){ /* when validation failed */ var html = '<div class="alert alert-danger alert-dismissible fade in" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + '<strong>Error!</strong><br />' + json.msg + '</div>'; /* place the message to msg-container */ $('#msg-container').html(html); } else { /* when validation success */ var html = '<div class="alert alert-success alert-dismissible fade in" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + '<strong>Error!</strong><br />Your data has been saved, thank you for regstering</div>'; /* clear the form when form submission is success */ theForm.find('input').val(''); /* place the message to msg-container */ $('#msg-container').html(html); /* do more things here, like redirect or other script..... */ } },'json'); //make sure the page notredirected when submit action is executed return false; });
So your final javascript file will be like this:
$(function(){ // Place the form object in variable to make easier to use latter var theForm = $('#form-data'); /* now we bind action when form submitted */ theForm.submit(function(){ /* run AJAX call */ $.post( theForm.attr('action'), theForm.serialize(), function(json){ if ( json.st === false ){ /* when validation failed */ var html = '<div class="alert alert-danger alert-dismissible fade in" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + '<strong>Error!</strong><br />' + json.msg + '</div>'; /* place the message to msg-container */ $('#msg-container').html(html); } else { /* when validation success */ var html = '<div class="alert alert-success alert-dismissible fade in" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + '<strong>Error!</strong><br />Your data has been saved, thank you for regstering</div>'; /* clear the form when form submission is success */ theForm.find('input').val(''); /* place the message to msg-container */ $('#msg-container').html(html); /* do more things here, like redirect or other script..... */ } },'json'); //make sure the page notredirected when submit action is executed return false; }); /* Enabling submit button. * You can prevent user submit form before all HTML DOM * loaded, which can result the page redirected and only shown an JSON * in your browser screen. */ $('.btn-submit').prop('disabled',false); });
Now try to reload your browser once again, and see if error message already shown in it’s container.



If you find your code has similar result with me then congratulation, with this approach, you can save your time, because now you only need to write validation code once for both client and server side.
But still this is only very simple example, you may need to add bunch of processing code when your validation is success, and maybe several security things 🙂
Download all final code here (code igniter controller, view & JS)
Okay, hope it useful for you, see you in next tips and trick 🙂