Learning Objectives
In this part you will how to perform form validation using jQuery.
Previous Parts
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:
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.
Fawwad Hassan, very thank you…
*ok, i’ll try for the exercise^^
Your welcome
Thanks!
I am learning a lot and appreciate your tutoring. I have been, and will continue to look forward to this series. I study the code between your publishing of these tutorials. I am looking forward for the next one.
Your welcome William
very nice man. keep it coming.
Excellent Work Bro !!!
liked the way you explained
Keep educating us….. :-p
Thanks everyone. I am busy in creating a new design for my blog which will be more usable. I apologize for the delay
Hello this is great. I have a few suggestions for future parts of this tutorial:
1. How to implement multiple column search,
2. How to implement a dialog form validation… Create form validation work perfect… but it does not work with update dialog form
Thanks for the suggestion Epitaph. I will surely include as much content as possible in this series
I appreciate a lot your blog. You’re a great man and thank you for the knowledge shared with us…
Awesome!!!
But, how to make a tab that consist of entry form and also table (below the form) to display the data?
Simply change the Html markup to move Create form in Read tab. Here’s the generic way to create tabs:
<div id=”tabs”>
<ul>
<li><a href=”#tab1″>TAB TITLE 1</a></li>
<li><a href=”#tab2″>TAB TITLE 2</a></li>
</ul>
<div id=”tab1″>
ADD CODE FOR RECORDS TABLE AND CREATE FORM HERE
</div>
<div id=”tab2″>CONTENT OF TAB 2 GOES HERE</div>
</div> <!– end tabs –>
Great, thank you for guiding me bro…
Now, i try to add header column but it won’t work. i just simply modify the tag like this:
User ID
Nama
Jabatan
Password
This modify successfully when i try in Part 1, but not in Part 5. Why it can happen?
ups, the html codes aren’t print here, i put the ‘th’ ‘/th’ syntax between the ‘table’ tag, but it can’t work on Part 5. Please give me some suggestion…
@zen we have the same problem, but my frend taught me how to show the table header, heres the solution:
add this on the readuser function right before
//clear old rows
$( ‘#records’ ).html( ” );
// make the header a string
str = “IDFirstnameLastnameBranch/DepartmentPositionAction”;
// then append the the table header
$(‘#records’).append(str);
Will you join pagination to this series of lessons
will be nice
While waiting for the lesson for pagination and sorting
) here’s a quick way to implement the table filter…
first download query.uitablefilter.js
http://novestranice.com/jquery.uitablefilter.js
In the head section add
below add
$(function() {
var theTable = $(‘table.filter1′)
theTable.find(“tbody > tr”).find(“td:eq(1)”).mousedown(function(){
$(this).prev().find(“:checkbox”).click()
});
$(“#filter”).keyup(function() {
$.uiTableFilter( theTable, this.value );
})
$(‘#filter-form’).submit(function(){
theTable.find(“tbody > tr:visible > td:eq(1)”).mousedown();
return false;
}).focus(); //Give focus to input field
});
find the line
and add a class attribute class=”filter1″
that’s it… very quick and easy
In my comment above missing parts of the html code
).. iFadey can you fix it? … I guess it was a some kind of protection …
however, see the implementation of the table filter here http://novestranice.com/table_filter.txt
Thanks sir for sharing your knowledge it helps us a lot. i have problem, why is it that when i create a user it doesn’t clear the input fields in the form?
i have a few suggestion sir:
1. How to Create a dynamic select list generated from the database.
2. How to update with select list base on the stored data.
Suggestion #1: already answered.. tnx
3. How to select multiple data and get the parent id and save in the database eg.
Cat1
Item1 = selected
Item2 = selected
Item3
thank you very much man youre blog is so interesting
hi hassan i want thank you very much for sharing knowledge.
but i have question in part1 of this series ( i cant reply in the part1 tut i think the replys is blocked by you )
anywhay my question is how to paginate this data ? is this possible to paginate this data using ci pagination class? or we must do something else?
please i need this. and thank you again
Comment posting automatically closes after 60 days since the tutorial is posted.
Pagination is possible in both ways (CI Pagination class OR using jQuery). Soon I will post next part of this series explaining how to paginate records.
thank you hassan im waiting for the next tut;
but i have one more question, in the part4 ‘update records’ usualy i check if the data provided existe already in database like this:
$this->db->where(‘username’,$username);
$query = $this->db->get(‘users’)->num-rows();
if($query > 0){
echo ‘error username already taken’;
}
else{
// update data goes her…
}
how can i do this with jquery, displaying a dialog box that tell the users that error
Create a new method in controller which returns a boolean value based on the existence of username. Call this method via Ajax call using jQuery before calling update method of controller.
Second option is to check username existence in the update method making update operation. E.g. in controller
function update() {
CHECK USERNAME EXISTENCE
IF USERNAME NOT EXISTS
THEN UPDATE and ECHO TRUE
ELSE ECHO FALSE
}
I hope you got the point. Try exploring yourself because I don’t want to spoil you folks by giving exact solution to everything. Hope you don’t mind
Really very good job, waiting for next series…. Thank you
Excellent tutorial dude. Loved the way you took the time to explain everything so extensively! Thanks.