CRUD using jQuery and Codeigniter – V

Learning Objectives

In this part you will how to perform form validation using jQuery.

Previous Parts

Get Source Files

Validation Plugin

I will use jQuery Validation Plugin in this tutorial because it’s very mature, easier to use, and also available on Microsoft’s Ajax CDN.

Click here to download the plugin. Then extract the zip file and copy jquery.validate.min.js in crud/js folder.

Now add this script in the view using following line of code:

<script type="text/javascript" src="js/jquery.validate.min.js"></script>

Using the Plugin

I am going to add validation in the create form. Open all.js from source files of Part 4. Now replace line 143 in all.js with the following line of code:

submitHandler: function( form ) {

Then on line 167, replace }); with closing brace }.

Now your code must look like following code.

submitHandler: function( form ) {
    $( '#ajaxLoadAni' ).fadeIn( 'slow' );
 
    $.ajax({
        url: 'index.php/home/create',
        type: 'POST',
        data: $( this ).serialize(),
 
        success: function( response ) {
            $( '#msgDialog > p' ).html( response );
            $( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
 
            //clear all input fields in create form
            $( 'input', this ).val( '' );
 
            //refresh list of users by reading it
            readUsers();
 
            //open Read tab
            $( '#tabs' ).tabs( 'select', 0 );
        }
    });
 
    return false;
}

All I have done is simply wrapped the code inside submit method with submitHandler function. The code in submitHandler is a simple Ajax call to create a new record. This code will run when validation will be successful. Also this code will be further wrapped in a validate method of jQuery Validate plugin as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// --- Create Record with Validation ---
$( '#create form' ).validate({
    rules: {
        cName: { required: true },
        cEmail: { required: true, email: true }
    },
 
    /*
    //uncomment this block of code if you want to display custom messages
    messages: {
        cName: { required: "Name is required." },
        cEmail: {
            required: "Email is required.",
            email: "Please enter valid email address."
        }
    },
    */
 
    submitHandler: function( form ) {
        $( '#ajaxLoadAni' ).fadeIn( 'slow' );
 
        $.ajax({
            url: 'index.php/home/create',
            type: 'POST',
            data: $( form ).serialize(),
 
            success: function( response ) {
                $( '#msgDialog > p' ).html( response );
                $( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
 
                //clear all input fields in create form
                $( 'input', this ).val( '' );
 
                //refresh list of users by reading it
                readUsers();
 
                //open Read tab
                $( '#tabs' ).tabs( 'select', 0 );
            }
        });
 
 
        return false;
    }
});

validate method is called on create form. On line 3 of above code snippet, rules are defined telling which form input fields to validate.

On line 4 is the first rule which tells the validate method that Name field is required. Similarly on line 5, second rule is defined which tells that Email field is required and must contain a valid email address.

On line 10 messages is commented out. Uncomment it if you want to define custom validation error messages. Otherwise default messages will be used.

On line 19 is the submitHandler which will automatically run when validation is successful. The code inside this handler is simply an Ajax call to perform CREATE operation which I already explained in previous part.

On line 25, I changed $( this ) to $( form ) because the keyword this in this handler now don’t point to create form. The form on which validation is performed is passed as a parameter to submitHandler. So I used the parameter form instead of this keyword.

Modify CSS

Validation error messages are displayed right next to the for input fields. They will be dynamically generated by the validation plugin. Also remember that by default these messages are wrapped in label tags having class “error”. So I am going to style label.error in create form as shown below.

/* Validation label */
#create label.error {
    color: red;
    font-size: .9em;
    padding: 4px;
    margin: 0 0 0 4px;
    width: auto;
}

You can customize how error messages are displayed. Check options errorElement and below to see how to change error message wrapper element, message placement and class name.

Now try submitting create form with empty values or with invalid email address. You will see output similar to this:

Validation using jQuery

More on Validation Plugin

To further learn about using validation plugin, I recommend you to read documentation. Specially check the possible options you can pass to validate method.

Exercise

I am validation in Update form for you as an exercise. Try it yourself and discuss issues in comments.

In next part I will cover table sorting, and pagination.


comments powered by Disqus