Form validation with jQuery and CodeIgniter

In this tutorial you will learn how to validate form fields with jQuery and CodeIgniter. We will use jQuery to validate in client side and PHP with CodeIgniter framework to validate server side. Therefore it will be very easy to follow this tutorial if you have basic knowledge of jQuery and CodeIgniter. Even if you don’t have knowledge of jQuery or CodeIgniter, it should not be a problem as i will start from very basics.

At the end of this tutorial, you can find a working example as well as all files to download.

2. Downloading required files:

We need jQuery and CodeIgniter framework as well as jQuery validation plugin.

The following latest versions (currently) are used in this tutorial.

  1. CodeIgniter (Version 2.0.2) Download
  2. jQuery (1.6.1) Download
  3. jQuery Validation Plugin: Download

Please note: Google provides hosting of jQuery on their CDN (Content Delivery Network) and let websites to use that. So you can either download the jQuery and place it in your folder, or you can use Google hosted jQuery file. If you want to use the Google hosted file, use by changing the source of jQuery in header file to:

https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js

3. Configuring the CodeIgniter:

We will need to autoload the url and form helpers in CodeIgniter. So open the application/autoload.php and add these helpers in line 67:

$autoload['helper'] = array('url', 'form');

4. The HTML Layout for the form:

The data in CodeIgniter is displayed in a View. Therefore we will write our form html code in a view, the same view will be displayed if there are any validation errors. However, if there are no any errors and form is validated successfully, we will load another view to display the success message.

First lets create a header and footer view so that we can include them in our form_view and success_view.

So lets create our views:

views/common/header.php

<!DOCTYPE>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Form Validation - Gazpo.com</title>
		<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style.css" />
		<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
		<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
		<script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>

    </head>
	<body>
		<div id="wrapper"> <!-- close it in footer -->

views/common/footer.php

		<div id="footer">
			<p> Tutorial by Gazpo.com.</p>
		</div>
	</div>  <!-- /wrapper  -->
	</body> <!-- closing body -->
</html>

Now we can include them in our form_view and success_view.

form_view.php

The form_view contains the html code of the form. I have included the different input types (text, radio, dropdown etc) to give example of validation of different input types.

I have used the CodeIgniter Form Helper’s form_open tag instead of html , as it creates the opening form tag with the base url.

<!-- include header -->
<?php $this->load->view('common/header'); ?>

	<!-- CodeIgniter Form tag -->
	<?php $attributes = array('id' => 'form');
	      echo form_open('form/process', $attributes); ?>

	<h2>Form Validation with CodeIgniter and jQuery</h2>

	<div class="field">
    <label for="name">Name</label>
    <input class="input" id="name" name="name" type="text" value="<?php echo set_value('name'); ?>" />
    </div>

	<div class="field">
    <label for="password">Password</label>
    <input class="input" id="password" name="password" type="password" value="<?php echo set_value('password'); ?>" />
    </div> 

	<div class="field">
    <label for="email">Email</label>
    <input class="input" id="email" name="email" type="text" value="<?php echo set_value('email'); ?>" />
    </div>	

	<div class="field">
	<label for="gender">Select Gender</label>
	<div class = "gender-fields">
	<input type="radio" class="radio" name="gender" value="male" <?php echo set_radio('gender', 'male'); ?>> Male
	<input type="radio" class="radio" name="gender" value="female" <?php echo set_radio('gender', 'female'); ?>> Female
	</div>
	</div> 

	<div class="field">
	<label for="state">Select State</label>
	<select class="state" name="state">
		<option class="droplist" ></option>
		<option class="droplist" value="Alabama" <?php echo set_select('state', 'Alabama'); ?> >Alabama</option>
		<option class="droplist" value="Alaska" <?php echo set_select('state', 'Alaska'); ?> >Alaska</option>
		<option class="droplist" value="Arizona" <?php echo set_select('state', 'Arizona'); ?> >Arizona</option>
	</select>
	</div>

	<div class="field">
	<label for="agree">Terms</label>
	<input type="checkbox" name="terms" class="checkbox" value="agree" <?php echo set_checkbox("terms","agree"); ?>/>
	</div>

	<input type="submit" name="submit" class="submit" value="Submit">
	</form>

<!-- include footer -->
<?php $this->load->view('common/footer'); ?>

views/success_view.php This view will be loaded if the form is validated successfully.

<!-- load header -->
<?php $this->load->view('common/header'); ?>

<!-- main content -->
<h3>Form was submitted successfully! </h3>

<!-- load footer -->
<?php $this->load->view('common/footer'); ?>

5. Styling the CSS layout:

Now we are done with our HTML layout. Lets add some CSS style to it.

body {
	font-family: arial,verdana,sans-serif;
	color:#333333;
	font-size:13px;
	margin: 0 auto;
    background: #f5f5f5;
	}

#wrapper {
	margin: 0 auto;
	position: relative;
	background:#FFFFFF;
	width: 900px;
	border:10px solid #eaeaea;
	}

#form {
	padding: 10px;
	}

#form .field {
	margin-bottom:15px;
	}

#form label{
    display: block;
	float: left;
	font-weight: bold;
	margin-right:10px;
	text-align: right;
	width: 120px;
	line-height: 35px;
	font-size:14px;
	cursor: pointer;
	} 

#form .checkbox{
	margin-top:10px;
	}

#form .input{
	-moz-border-radius: 7px;
	-webkit-border-radius: 7px;
	background-color: #eaeaea;
	background: -moz-linear-gradient(top, #ffffff, #f2f2f2);
	background: -webkit-gradient(linear, left top, left bottom,
				color-stop(0.0, #ffffff), color-stop(1.0, #f2f2f2));
	border: 1px solid #cacaca;
	font-family: inherit;
	color: #797979;
	font-size: 15px;
	padding: 8px 10px;
	width: 300px;
	font-weight: bold;
	}

#form .state{
  	border: 1px solid #b9bdc1;
  	padding: 5px;
  	font-size: 15px;
  	font-family: inherit;
  	font-weight: bold;
  	color: #797979;
	}

#form :focus{
  	-webkit-box-shadow: 0px 0px 4px #aaa;
	-moz-box-shadow: 0px 0px 4px #aaa;
	box-shadow: 0px 0px 4px #aaa;
	}

#form .gender-fields{
	padding-top:10px;
	}

	#form  span.error {
	color:red;
	padding-left:10px;
	}

#form .info{
	margin-left:130px;
	font-size: 12px;
	font-style:italic;
	color: #999;
	}

#form .submit{
	-moz-border-radius: 15px;
	-webkit-border-radius: 15px;
	font-family: arial,verdana,sans-serif;
	background-color: #dedede;
	background: -moz-linear-gradient(top, #ffffff, #eaeaea);
	background: -webkit-gradient(linear, left top, left bottom,
				color-stop(0.0, #ffffff), color-stop(1.0, #eaeaea));
	border: 1px solid #dedede;
	color: #484848;
	font-size:14px;
	font-weight: bold;
	padding: 8px 10px;
	cursor: pointer;
	margin-left:220px;
	}

/*-- Table design to display data in success view --*/

#display_data{
padding:10px;
}

#display_data .name{
	font-style: italic;
	text-decoration:underline;
	}

#display_data table{
	border:1px solid #e5eff8;
	margin:10px 0px;
	border-collapse:collapse;
	}

#display_data tr.even{
	background:#f7fbff
	}

#display_data tr.odd .title {
	background:#f4f9fe;
	}

#display_data td {
	border-bottom:1px solid #e5eff8;
	border-right:1px solid #e5eff8;
	color:#678197;
	padding:5px 8px;
	}

#display_data td.title{
	font-weight: bold;
	width:100px;
	text-align:right;
	}

#display_data td.info{
	font-style: italic;
	width:200px;
	}

#footer {
	width:60%;
	margin:20px auto;

	}

6. Form Controller

We need to create a controller to load and process the form. So, create a controller called form.php in application/controllers/

In the index function of the controller we can simply load the form:

class Form extends CI_Controller {
	public function index()
	{
		$this->load->view('form_view');
	}

Now we should be able to access the form with the url like:

http://localhost/form_validation/index.php/form

Our form will look like:

7. Validation with jQuery

This jQuery validation plugin provides built-in validation methods such as email, date, phone, zip codes, credit card, numeric, URLs etc.

We can define the rules to validate the form fields, for example:

email: {
		required: true,
		email: true
		},

Similarly some rules for name field:

name: {
			required: true,
			minlength: 3,
			maxlength:25,
		},

Simple, isn’t it? We just used the built-in methods to validate our input fields. For example for name input, we defined that it is required field and it should be between 3 to 25 characters.

However, we want to allow only alphabets in the name field, we don’t want to accept any numbers or special characters. We can define our own method for that:

$.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[a-z]+$/i.test(value);
			}, "Please enter only letters");

Following is complete javascript code for the validation rules:

js/validation_rules.js

	$(document).ready(function() {
		jQuery.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[a-z]+$/i.test(value);
		}, "Please enter only letters"); 

		// validate contact form on keyup and submit
		$("#form").validate({

			//set the rules for the fild names
			rules: {
				name: {
					required: true,
					minlength: 3,
					maxlength:25,
					lettersonly: true
				},
				email: {
					required: true,
					email: true
				},
				password: {
					required: true,
					minlength: 5,
					maxlength:15
				},
				gender : {
					required :true
				},
				state : {
					required :true
				},
				terms: {
					required :true
				},
			},

			//set error messages
			messages: {

				name: {
					required: "Name is required..",
				},
				password: {
				required: "Please provide a password.",
				minlength: "Password must be at least 5 characters long",
				maxlength: "Password can not be more than 15 characters"
				},
				email: "Valid email is required.",
				terms: "You must agree to our terms.",
				gender: "Gender is required",
				state: "Select state"
			},

			//our custom error placement
			errorElement: "span",
			errorPlacement: function(error, element) {
					error.appendTo(element.parent());
				}

		});
	});

8. Server side validation with CodeIgniter:

Lets get back to our form controller and create a function called process, where the form will be processed.

First we need to load the validation class:

$this -> load -> library( 'form_validation' );

Setting Validation Rules:

Now we can set CodeIgniter validation rules as:

$this->form_validation->set_rules('field name', 'Name to display', 'Rule');

For example the name field:

$this -> form_validation -> set_rules( 'name', 'Name', 'trim|required|alpha|min_length[3]|max_length[25]' );

The required rule makes sure that the field is not blank, while the valid_email ensures that a valid email address is provided. The alpha rule checks if the input contains only alphabetical characters. We define the minimum and maximum length of input with min_length and max_length rules respectively.

Now if there is any validation error, we should load the form_view again with the errors. If there is no any error, then obviously we don’t want to load the form_view again, instead we want to load the success_view. So lets write code for that:

if ( $this -> form_validation -> run() === FALSE )
	{
			$this -> load -> view( 'form_view' );
    }
	else
	{
		$this -> load -> view( 'success_view' );
	}

Displaying Form Errors:

We need to add following code next to each field in our form_view to display the errors:

<?php echo form_error('field name'); ?>

For example:

<div class="field">
        <label for="name">Name</label>
        <input class="input" id="name" name="name" type="text" />
        <?php echo form_error('name'); ?>
</div>

By default CodeIgniter displays error message in a paragraph tag. We can change this and use the tag of our own choice. For example I would like to display the error messages in a span tag. So we need to add following line in our controller function just after loading the validation library.

$this -> form_validation -> set_error_delimiters('<span class="error">', '</span>');

Now the form will display the validation rules next to each field in a span tag.

If the validation is successful, we can clean the input and store it in database or whatever we want to do with it. In this tutorial, we will not use database, instead lets just pass the input data to our success_view:

//clean the input
$this -> name 	  = $this -> security -> xss_clean( $this -> input -> post( 'name' ) );
$this -> email 	  = $this -> security -> xss_clean( $this -> input -> post( 'email' ));

//load the data
$data['name'] 	  = $this -> name;
$data['password'] = $this -> password;
$this -> load -> vars( $data );
$this -> load -> view( 'success_view' );

Complete code for our form controller will be:

application/controllers/form.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Form extends CI_Controller {

	public function index()
	{
		$this->load->view('form_view');
	}

	public function process()
	{

		$this -> load -> library( 'form_validation' );
		$this -> form_validation -> set_error_delimiters('<span class="error">', '</span>');

		$this -> form_validation -> set_rules( 'name', 'Name', 'trim|required|alpha|min_length[3]|max_length[15]' );
		$this -> form_validation -> set_rules( 'password', 'Password', 'trim|required|min_length[4]|max_length[15]' );
		$this -> form_validation -> set_rules( 'email', 'Email address', 'trim|required|valid_email' );
		$this -> form_validation -> set_rules( 'gender', 'Gender', 'required' );
		$this -> form_validation -> set_rules( 'state', 'State', 'required' );
		$this -> form_validation -> set_rules( 'terms', 'Terms', 'required' );

		//Setting custom error messages
		$this -> form_validation -> set_message( 'min_length', 'Minimum length for %s is %s characters');
		$this -> form_validation -> set_message( 'max_length', 'Maximum length for %s is %s characters');

		if ( $this -> form_validation -> run() === FALSE )
		{
			$this -> load -> view( 'form_view' );
        }
        else
        {
        	//Form validation is successful, clean the input and use it.
        	//For example store in db (In this tutorial we wont use database).
        	$this -> name 	  = $this -> security -> xss_clean( $this -> input -> post( 'name' ) );
        	$this -> password = $this -> security -> xss_clean( $this -> input -> post( 'password' ) );
        	$this -> email 	  = $this -> security -> xss_clean( $this -> input -> post( 'email' ));
        	$this -> gender   = $this -> input -> post( 'gender' );
        	$this -> state    = $this -> input -> post( 'state' );
        	$this -> terms 	  = $this -> input -> post( 'terms' ); 

        	//Since we are not storing it to database,
        	//lets send this data to our success view to display there.
        	$data['name'] 	  = $this -> name;
        	$data['password'] = $this -> password;
        	$data['email'] 	  = $this -> email;
        	$data['gender']   = $this -> gender;
        	$data['state'] 	  = $this -> state;
        	$data['terms']	  = $this -> terms;

        	//load the data and success view.
        	$this -> load -> vars( $data );
        	$this -> load -> view( 'success_view' );
        }

	}

}

/* End of file form.php */
/* Location: ./application/controllers/form.php */

Recieving data on success_view:

As we sent the data to the success_view from our controller, we can receive it using the same variables, for example:

<?php echo $name; ?>

So, open the success_view and write the following code to get the form input data:

views/success_view.php

<?php $this->load->view('common/header'); ?>

<div id ="display_data">
	<h1>Thank you,  <span class="name"><?php echo $name; ?></span></h1>
	<h3>Form was submitted successfully! </h3>
	<h4>We have received following data:</h4>

<table>
	<tr class="odd">
		<td class="title">Your name: </td>
		<td class="info" ><?php echo $name; ?></td>
	</tr>

	<tr class="even">
		<td class="title">Email:</td>
		<td class="info"><?php echo $email; ?></td>
	</tr>

	<tr class="odd">
		<td class="title">Password:</td>
		<td class="info"><?php echo $password; ?></td>
	</tr>

	<tr class="even">
		<td class="title">Gender:</td>
		<td class="info"><?php echo $gender; ?></td>
	</tr>

	<tr class="odd">
		<td class="title">State:</td>
		<td class="info"><?php echo $state; ?></td>
	</tr>

	<tr class="even">
		<td class="title">Terms:</td>
		<td class="info"><?php echo $terms; ?></td>
	</tr>

</table>
</div>
<?php $this->load->view('common/footer'); ?>

Thats all  :) You can view the demo of the form and download the code below :)

If you did not understand something, please leave a comment.
PS. Thanks to ScottO (view comments below) for mentioning the error and suggesting the improvements in form_view.

  • http://Website Rain

    hi i like your tutorial!!!

    if i want to have 1 more field which is “confirm password” field

    and this field must match the “password” field

    how could i do the validation for “password” and “confirm password” fields

    please help me

    thank you so much

    • Free Gallery Template

      Hi, you create input with id=”password1″

      in the rule, you add the following

      password1: {
      required: true,
      equalTo: “#password”
      }

      http://themescss.com

  • Sam

    @Rain: Glad that you liked the tutorial :)
    If you want to add an additional field to confirm password and it should match the password field, here’s what you should do.
    1. Add an input field in the form_view.php and name it “passconf” Or whatever you want.
    2. In controller, you need to add another rule “matches[passconf]” for the password field, which basically tells the password field that it should match with the passconf field.

    3. You should set ‘required rule’ for your passconf field as well.

    So your rules for both fields should be:
    $this -> form_validation -> set_rules( ‘password’, ‘Password’, ‘trim|required|matches[passconf]|min_length[4]|max_length[15]‘ );
    $this->form_validation->set_rules(‘passconf’, ‘Password Confirmation’, ‘trim|required’);

    Hope it helps :)

    • Yannick

      Yes this does work, but not if you want to validate with jQuery, without refreshing the page. Anyone a solution? And I’m stuck at one problem more: how can I validate if a username or email address already exists? I know how to validate this with codeigniter but not with this jQuery plugin.

  • http://www.facebook.com/people/Radu-Cel-Frumos/100002038332008 Radu Cel Frumos

    thanks a lot

    • http://gazpo.com Sam

      you’re welcome :)

  • Thomasoriis

    Nice implementation I think – I will test it in my solution tomorrow.

    Have had it with onsubmit giving me a blank page.

    Thx ; )

  • digital site

    great tut. one of the best so far. I got a question please. I get this error all times and don’t know how to deal with it:
    PHP Fatal error: Class ‘MathGuard’ not found in….. any idea how to resolve this issue. Thanks

  • Rami Hamdan

    thanks alot man I was really need the set error message function cause its the only way that is working and very fast 

  • ScottO

    This is really a very nice tutorial, not only technically, but the layout.  Nicely done.  Only one issue that I see, and maybe this only applies to the demo you posted, is that the form didn’t repopulate the data when an error is encountered.  For example, if I fill out the demo form and do not check the checkbox, then click submit, the form will catch that I didn’t check the box, but only after the submit and it wipes out all my entries and tells me the checkbox is required.

  • ScottO

    Been playing with this and now have the checkbox working, though I’m not crystal clear on which change made this work correctly:

    1) used the latest jquery.validate.js (version 1.9) because it had an entry that talked about a fix for checkboxes, though I know for sure this was not the fix alone.  I updated to this version and the issue still existed.

    2) I noticed the id of the “terms” object seems to be referenced as “agree” in a couple places, so I changed the “agree” to be “terms” and this now works.  The two places I made the changes were: Form_view.php (line 51) and jquery.validate-rules.js (line 60)

    I hope this helps others.  Now on to test and see what happens if the server side validations fail – really want the form to not lose the user’s data and simply identify the errored field.

  • ScottO

    Yeah, it’s me again.  Bent on getting this stuff figured out… So here’s the final solution to get the form to repopulate with the user’s data….  Here’s the full code from my version of the form_view.php file which is now even remembering the user’s selections on the gender radio buttons, the checkbox, and the dropdown value for the state:

    [code]
    load->view('common/header'); ?> 'form'); echo form_open('form/process', $attributes); ?> Form Validation with CodeIgniter and jQuery                  Name                  <input class="input" id="name" name="name" type="text"  value="" />                                                       Password                  <input class="input" id="password" name="password" type="password"  value="" />                                                Email                  <input class="input" id="email" name="email" type="text"  value="" />                                                      Select Gender <input type="radio" class="radio" name="gender" value="male" /> Male <input type="radio" class="radio" name="gender" value="female" /> Female       Select State <option class="droplist" value=" " > <option class="droplist" value="Alabama" >Alabama <option class="droplist" value="Alaska" >Alaska <option class="droplist" value="Arizona" >Arizona     Terms <input type="checkbox" name="terms" class="checkbox" value="agree" />   load->view('common/footer'); ?>
    [end code]

    • ScottO

      Since the code didn’t display correctly (some parts dropped out completely), I’ve emailed the solution to Gazp.  Hopefully they’ll pick it up and integrate it, along with the checkbox correction below, to make this tutorial fully complete for everyone to learn from.

      • http://gazpo.com Sami

        Thanks ScottO, I have updated the post above.

  • thequickbrownfoxjumps

    thequi

  • sreejith

    Hi,

    This is a wonderful tutorial. Thanks for sharing.

    But I have a small doubt. What if I want to validate only server side?. I dont want to use Jquery plugin. Then how will be my AJAX code. Please help..

    regards

  • Hasan Raza

    Nice

  • adsem
  • sakthi

    when i run this program i have an error like

    Access forbidden!

    You don’t have permission to access the requested object.
    It is either read-protected or not readable by the server.

    If you think this is a server error, please contact
    the webmaster.

    Error 403

    localhost

    Can u pls tell me wat error is this..sry im not femiliar in jquery and codeigniter..so pls can u help me..

    Apache/2.4.3 (Unix) OpenSSL/1.0.1c PHP/5.4.7