Yavor Atanasov web portfolio

Weblog

2010
02.27
1. Introduction

CI_jQuery_validation In a dynamic web application the database is the heart that keeps it alive pumping data in and out. The database is the very core that holds the essence of that application – the data in its basic form. That core is then wrapped with the application layer that holds all logic and operations that seal that data and control its communication with the outer world. A web application is like a living cell and if something malignant enters its nucleus, it dies or becomes harmful.
The web forms are a peculiar HTML element because they provide a pathway for external input leading to the data core of the web application. Therefore, what happens to that external input along the way before it enters the database is of crucial importance. The input must be scanned and cleaned with great precision before it becomes pure data and “qualifies” for database insertion. This is what makes data pure:

  • Its data type and format matches the one the database expects
  • Its length does not exceed the limit the database field can hold
  • Escape sequences and special characters should be filtered to prevent SQL injections which can be detrimental to the data integrity
  • Client-side scripts (JavaScript) should be recognized and filtered to prevent potential cross-site scripting (XSS)

This is where form validation kicks in. Form validation can be divided into two separate layers – client-side and server-side validation.

2. Client-side vs Server-side validation

Essentially both types of validation (client-side and server-side) are the very same thing, only the place where they are executed is different. Exactly that difference, however, defines the way we look at those two layers of validation. Client-side validation should be looked upon more like a usability enhancement that helps users with good intentions and bad typing. It is fast and users do not have to wait for a server response to understand they had input wrong data. JavaScript, however, can easily be disabled (presumably by users with bad intentions) thus removing the client-side layer of defense. Therefore, validation on the server is absolutely mandatory.

3. CodeignIter and server-side validation

Codeigniter is a great open-source PHP MVC framework that is loaded in terms of functionality and yet very light and excellently documented. Here you can find an excellent tutorial to get you started with CodeIgniter if it is completely new for you.
CodeIgniter comes with a built-in Form Validation Class and a Form Helper for fast and effective form building. This is how they can be used to quickly create a form and secure it on the server.

3.1 Setting up the View
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<title>CodeIgntier Form</title>
<link rel="stylesheet" type="text/css" href="<?php echo $base .‘css/main.css’;?>"/>
<script src="<?php echo $base .‘js/jquery-1.4.1.min.js’;?>" type="text/javascript"></script>
<script src="<?php echo $base .‘js/jquery.validate.min.js’;?>" type="text/javascript"></script>
<script src="<?php echo $base .‘js/additional-methods.js’;?>" type="text/javascript"></script>
<script src="<?php echo $base .‘js/form_implementation.js’;?>" type="text/javascript"></script>
</head>
<body>
<?php
$attributes = array(‘id’ => ‘myform’);
echo form_open(‘form/send’, $attributes);
$attributes = array(‘id’ => ‘personal_info’);
echo form_fieldset(‘Personal information’, $attributes);
echo form_label(‘Your name’, ‘name_field’);
$attributes = array(
              ‘name’        => ‘name’,
              ‘id’          => ‘name_field’
            );
echo form_input($attributes);
echo form_error(‘name’);
echo form_label(‘Your email’, ‘email_field’);
$attributes = array(
              ‘name’        => ‘email’,
              ‘id’          => ‘email_field’
            );
echo form_input($attributes);
echo form_error(‘email’);
echo form_submit(‘submit’, ‘Submit’);
echo form_fieldset_close();
echo form_close();
?>
</body>
</html>

The output in the browser generated by this is view can be seen in figure 1. As CSS styling is not in the agenda of this article, I am not going to comment on it. The CSS file can be found with all source files here.

codeigniter form view

Figure 1. The form generated by the view

3.2 Setting up the Controller

The first thing that needs to be done is setting up the appropriate controller object:

<?php
class Form extends Controller {
        function Form()
        {
                parent::Controller();
                $this->load->helper(‘form’);
        }
        function index()
        {
                $data[‘base’] = $this->config->item(‘base_url’);
                $this->load->view(‘form_view’, $data);
        }
        function send(){
                $this->load->library(‘form_validation’);
                $this->form_validation->set_error_delimiters(‘<div class="error"><p>’, ‘</p></div>’);
                $this->form_validation->set_rules(‘name’, ‘Your name’, ‘required|alpha_numeric|max_length[45]‘);
                $this->form_validation->set_rules(‘email’, ‘Your email’, ‘required|valid_email|max_length[45]‘);
                $this->form_validation->set_message(‘required’, ‘Required field’);
                $this->form_validation->set_message(‘max_length’, ‘No more than 45 characters’);
                $this->form_validation->set_message(‘valid_email’, ‘Please enter a valid email’);
                $this->form_validation->set_message(‘alpha_numeric’, ‘Only letters and numbers are allowed here.’);
        if ($this->form_validation->run() == FALSE) {
                        $data[‘base’] = $this->config->item(‘base_url’);
                        $this->load->view(‘form_view’, $data);
        }
        }
}
/* End of file form.php */
/* Location: ./system/application/controllers/form.php */
?>

This is a pretty generic and simple CodeIgniter controller consisting of a constructor, index function and a send function that will process the form later on. One thing to notice is that the Form helper is loaded in the constructor. The index function is the default function executed when the controller is called (unless a different function is specified in the URL). All we do in the index function in this case is load the base URL of our application from the config file so it can be passed to the view via the $data array. The send function is going to be the function called in the action attribute of the form.
The send function loads the Form Validation class from the library and sets the rules for the corresponding form fields, specified by field name. The set_rules function takes three parameters:

  • the field name as specified in your form
  • A “human” name for that field in case you want to store that in a language file (more on this here)
  • the set of rules that will apply for the corresponding field (the full list of rules can be found here)

If the validation fails (returns false), the controller returns the user to the form view again displaying the corresponding error messages.

codeigniter validation form with errors

Figure 2. The form returned after failed validation

4. jQuery validation

A great way to validate a form on the client machine with jQuery is via a plug-in called Validation. This is how the implementation of this plug-in looks like:

$(document).ready(function(){
    $("#myform").validate({
        rules: {
            name: {
                required:true,
                alphanumeric:true,
                maxlength: 45
            },
            email: {
                required: true,
                email: true,
                maxlength: 45
            }
        },
        messages: {
            name: {
                required:"It would be nice if I know who you are.",
                alphanumeric:"This field should not contain any funny characters",
                maxlength:"My dissertation is shorter than your name :) Give me a nickname."
            },
            email:  {
                required:"Please enter your email address.",
                email:"Oh, come on, this is not an email, you know that!",
                maxlength:"Maximum characters allowed – 45"
            }
        },
        invalidHandler:function(){
        }
        })
});//document ready close

This way the user does not have to wait a trip to the server and back to understand he/she has entered something wrong.

jQuery form validation example

Figure 3. Errors if nothing is submitted.

jQuery form validation example

Figure 4. Errors when the input is the wrong type

5. Source files

All source code files used in this example can be downloaded here.

4 comments so far

Add Your Comment
  1. hey thanks for this i think i will use this on a project! :D

  2. I’m glad it helped :) If you’d like to go even more extreme with form security, you might want to check this out as well. Greetings to Kentucky :)

  3. Thats awesome man, two thumbs up !!

  4. great article.
    thanks man…

Your Comment