JQuery Starter


Table of Contents

  1. How Will We Achieve That?
  2. Project Structure
  3. Coding the HTML
  4. Spicing It Up With CSS
  5. All The Fun: jQuery Magic
  6. Final Product
  7. After Word

How Will We Achieve That?

Now, there are actually many ways to do that; here are the most common:

  1. We could put </span> (which will be holding validation info) next to our form field and give it an ID so we can easily access its content later
  2. We could wrap every field in </p> with applied ID, and put </span> (which will be holding validation info) inside it, so we can easily access its content, through that </p>‘s child-span
  3. We could wrap every field in </p> with applied ID, and inject </span> with validation info to it

It will all work, but neither is the optimal way. Why? Because there’s too much messing with your HTML code and you’ll end up with bunch of needless tags that are required by your validation script, but which your form doesn’t really need.

It’s clearly not the way to go, so instead we’re going to do this the way I do it myself. In my opinion it’s the best solution, although it’s not very common; I honestly have never came across this method, I’ve never seen it used by someone. But if you have, please let me know in the comments.

OK, so what are we going to do?

  1. We’re going to write simplest form possible, nice and clean, no unnecessary tags whatsoever
  2. As the user fills out particular field, we’re goinng to validate it on the fly and:
    • grab its position in the window (top and left)
    • grab its width
    • add width and the left offset (from the field’s position) together so we know where the field ends
    • put validation info into </div> with applied ID, inject it to the document, position it absolutely on the spot where the field ends, and manipulate its class as needed (for example .correct or .incorrect)

That way we keep our HTML code nice and clean.

Note: It’s vital to always provide server-side validation as well (for users with turned off JavaScript).

Project Structure

We are going to need three files:

  • index.html
  • style.css
  • validation.js

I’m gonna go roughly through the HTML coding, provide you with all needed CSS – and then focus mostly on our jQuery script, which is the most important thing and what we’re hoping to learn today.

Coding the HTML

Step 1: Some Basic HTML and Importing jQuery + Validation Script

First, make index.html file and put some basic code there; you can see that we imported jQuery at the bottom, along with our validation.js file, which will contain our validation script:

1 <!--DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>Real-Time Form Validation Using jQuery</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
7 </head>
8 <body>
9
10 <div id="content">
11
12 </div><!-- content -->
13
14 <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" charset="utf-8"></script>
15 <script type="text/javascript" src="validate.js" charset="utf-8"></script>
16 </body>
17 </html>

Step 2: The Form, Splitted Into Three Sections

We’re going to split the form into three sections using </fieldset>, and </label> for each section headline:

  1. Personal Info (user name, date of birth, gender, vehicles)
  2. Email (user’s email adress)
  3. About (little info about the user)
1 <!--DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>Real-Time Form Validation Using jQuery</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
7 </head>
8 <body>
9
10 <div id="content">
11 <form id="jform" action="http://1stwebdesigner.com" method="post">
12     <fieldset>
13         <legend>Personal Info</legend>
14     </fieldset>
15
16     <fieldset>
17         <legend>Email</legend>
18     </fieldset>
19
20     <fieldset>
21         <legend>About You</legend>
22     </fieldset>
23 </form>
24 </div><!-- content -->
25
26 <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" charset="utf-8"></script>
27 <script type="text/javascript" src="validate.js" charset="utf-8"></script>
28 </body>
29 </html>

Step 3: Adding Fields + Submit Button

Great, now it’s time to finally add some fields to our form. For this tutorial we’re going to use several different fields:

  • three text inputs: for user’s full name, date of birth and email adress
  • radio buttons for user’s gender
  • checkboxes for vehicles owned by the user
  • textarea for little info about the user
  • button for submit button

We’re going to wrap every set (label + field) in </p> to keep them separated and display them as blocks.

Your final index.html file should look like this:

1 <!--DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>Real-Time Form Validation Using jQuery</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
7 </head>
8 <body>
9
10 <div id="content">
11     <form id="jform" action="http://1stwebdesigner.com" method="post">
12         <fieldset>
13             <legend>Personal Info</legend>
14             <p>
15                 <label for="fullname" class="block">Full name:</label>
16                 <input type="text" name="fullname" id="fullname" />
17             </p>
18             <p>
19                 <label for="birthday" class="block">Day of birth <small>(dd-mm-yyyy)</small>:</label>
20                 <input type="text" name="birthday" id="birthday" />
21             </p>
22             <p>
23                 <label class="block">I am:</label>
24                 <input type="radio" name="gender" id="man" value="man" /> <labelfor="man">Man</label>
25                 <input type="radio" name="gender" id="woman" value="woman" /> <labelfor="woman">Woman</label>
26             </p>
27             <p>
28                 <label class="block">I own:</label>
29                 <input type="checkbox" name="vehicle" id="car" /> <label for="car">car</label>
30                 <input type="checkbox" name="vehicle" id="airplane" /> <labelfor="airplane">airplane</label>
31                 <input type="checkbox" name="vehicle" id="bicycle" /> <labelfor="bicycle">bicycle</label>
32                 <input type="checkbox" name="vehicle" id="ship" /> <labelfor="ship">ship</label>
33             </p>
34         </fieldset>
35
36         <fieldset>
37             <legend>Email</legend>
38             <p>
39                 <label for="email" class="block">Email <small>(mickey@mou.se)</small>:</label>
40                 <input type="text" name="email" id="email" />
41             </p>
42         </fieldset>
43
44         <fieldset>
45             <legend>About You</legend>
46             <p>
47                 <label for="about" class="block">Tell us a little bit about yourself:</label>
48                 <textarea id="about" cols="50" rows="10"></textarea>
49             </p>
50         </fieldset>
51         <p>
52             <button type="submit" id="send">submit</button>
53         </p>
54     </form>
55 </div><!-- content -->
56
57 <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" charset="utf-8"></script>
58 <script type="text/javascript" src="validate.js" charset="utf-8"></script>
59 </body>
60 </html>

It may look a bit messy, but it’s because of the WP’s syntax highlighting plugin. It’s actually really clean, and that’s what we wanted to achieve afterall. Check it: save the above code as your index.html file, open it in your browser and look at the source code. Now it looks clean, isn’t it?

Spicing It Up With CSS

Since CSS styling is not our main focus in this tutorial, I’m not gonna go over this, but simply provide you with the CSS you’re going to need for this to work.

Create style.css file, put inside all the code from below and that’s it! Now everything should look sweet.

1 body {
2     background#efefef;
3     margin0;
4     padding0;
5     bordernone;
6     text-aligncenter;
7     fontnormal 13px Georgia, "Times New Roman", Times, serif;
8     color#222;
9 }
10
11 #content {
12     width500px;
13     margin0 auto;
14     margin-bottom25px;
15     padding0;
16     text-alignleft;
17 }
18
19 fieldset {
20     margin-top25px;
21     padding15px;
22     border1px solid #d1d1d1;
23     -webkit-border-radius: 7px;
24     -moz-border-radius: 7px;
25     border-radius: 7px;
26
27 }
28
29 fieldset legend {
30     fontnormal 30px VerdanaArialHelveticasans-serif;
31     text-shadow0 1px 1px #fff;
32     letter-spacing-1px;
33     color#273953;
34 }
35
36 input, textarea {
37     padding3px;
38 }
39
40 label {
41     cursorpointer;
42 }
43
44 .block {
45     displayblock;
46 }
47
48 small {
49     letter-spacing1px;
50     font-size11px;
51     font-styleitalic;
52     color#9e9e9e;
53 }
54
55 .info {
56     text-alignleft;
57     padding5px;
58     font-size11px;
59     color#fff;
60     positionabsolute;
61     displaynone;
62     -webkit-border-radius: 5px;
63     -moz-border-radius: 5px;
64     border-radius: 5px;
65     -webkit-box-shadow: -1px 1px 2px #a9a9a9;
66     -moz-box-shadow: -1px 1px 2px #a9a9a9;
67     box-shadow: -1px 1px 2px #a9a9a9;
68 }
69
70 .error {
71     background#f60000;
72     border3px solid #d50000;
73
74 }
75
76 .correct {
77     background#56d800;
78     border3px solid #008000;
79 }
80
81 .wrong {
82     font-weightbold;
83     color#e90000;
84 }
85
86 .normal {
87     font-weightnormal;
88     color#222;
89 }
90
91 #send {
92     background#3f5a81;
93     width100%;
94     border5px solid #0F1620;
95     fontbold 30px Verdanasans-serif;
96     color#fafafa;
97     text-shadow1px 1px 1px #0F1620;
98     -webkit-border-radius: 7px;
99     -moz-border-radius: 7px;
100     border-radius: 7px;
101 }
102
103 #send:hover {
104     background#4d76b1;
105     border5px solid #253750;
106     color#fff;
107 }
108
109 #send:active {
110     text-indent-10px;
111 }

All The Fun: jQuery Magic

This is the most interesting and engaging part. First we need to do some thinking and describe our key points.

Step 1: Planning

We have to ask ourselves three questions before we can go on:

  1. What do we need the script to do?
  2. How do we want it to do this?
  3. How do we achieve that?

It’s obvious we want the script to validate our form. But how?

  • we want to be able to validate it both in real-time (when user is filling it out) and on the form submit
  • therefore we need to make a “pack” of functions responsible for each of its fields, so we can call them:
    • individually, when the user is filling out particular field
    • all at once, on the form submit

To reduce our global footpring, we’re going to use JavaScript object for that.

Step: 2: What Do We Need?

JS object, in our case it will be:

  • jVal

Methods of that object for each of the form fields, validating that particular field:

  • jVal.fullName
  • jVal.birthDate
  • jVal.gender
  • jVal.vehicle
  • jVal.email
  • jVal.about

Variable which will hold the status of error occuring:

  • jVal.errors

And method that will be called as the last one; it will check if there were any errors and submit the form if not. If some errors occurred, it will take the user to the beginning of the form, so they can fill it out again.

  • jVal.sendIt

Now we can finally start building our validation script. When finish our first validation method, then it will be much easier and faster, as we can reuse it for other methods, only applying some changes. Let’s crack into it!

Step 3: Our Script “Packaging”

The start is really simple, almost everything will go inside this code:

1 $(document).ready(function(){
2     jVal = {
3
4     };
5 });

Step 4: Validating User’s Name

Our first method will handle user’s name. Put it inside our jVal object, like this:

1 var jVal = {
2     'fullName' function() {
3
4     }
5 };

Now let’s put some first lines of code inside our method. Just paste it, and then I will explain what the code “says”:

1 $('body').append('
<div id="nameInfo”>

');

2
3 var nameInfo = $('#nameInfo');
4 var ele = $('#fullname');
5 var pos = ele.offset();
  • Line 1: We’re injecting </div> to the document. Class “info” gives it some styling (defined in our CSS file) and also make it invisible by setting display to “none” – so it’s there, but we don’t see it yet. As for the ID, it’s for easy “grabbing” and manipulating, since it will be positioned absolutely in the document. This </div> will contain our validation info that will be showed to the user, so they know if they filled out the field correctly.
  • Line 3: We’re assigning our </div> to the variable nameInfo, because we’ll be using it couple times more.
  • Line 4: We’re assigning our form field with ID “fullname” to the variable ele. The same reason as above, we will use it several times later.
  • jQuery function offset() returns current position of an element relative to the document. It returns an object containing the properties top and left. We used this function on our ele (which is actually form input with ID“fullname”), so it will return position of that element, which we assign to the variable pos.

Great, so far so good. It’s time to add some few more lines:

1 nameInfo.css({
2     top: pos.top-3,
3     left: pos.left+ele.width()+15
4 });
  • Line 2: We start to operate on nameInfo‘s CSS top property. Remember, our variable pos holds now the position of our form input with ID “fullname” in the document. We access its top value by simply joining poswith the word top using period . Then we decrement that by 3 and assign it to the CSS top property of ournameInfo element.
  • Line 3: We start to operate on nameInfo‘s CSS left property. We access left value of our “Full name” input’s position, increase it by its width (we grab that from calling jQuery function width() on our ele element) and increase it by 15. The result is assigned to the CSS left property of our nameInfo element.

We’re doing really great, we just acomplished 50% of fullName, our first validating method. It’s time to actually check if the user filled our “Full name” field correctly or not, and take appropriate action:

1 if(ele.val().length < 6) {
2     jVal.errors = true;
3         nameInfo.removeClass('correct').addClass('error').html('&larr; at least 6 characters').show();
4         ele.removeClass('normal').addClass('wrong');
5 else {
6         nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
7         ele.removeClass('wrong').addClass('normal');
8 }

Lot of weird crap, huh? Don’t worry, it’s not so scary as it may look:

  • Line 1: We’re checking if the name that user typed in is shorter than 6 characters.
  • Line 2: We set our object’s variable jVal.errors to true, as we just got our first error (user’s name is too short). We’re going to use it later.
  • Line 3: We start to operate on our nameInfo element (which is the </div> we’re gonna display validation info in). First we remove the class “correct”; it may be applied to our nameInfo element from previous validation (if it was performed). Then we apply the class “error” to it. Next, we put content to our nameInfo element, it’s the information that the name should be at least 6 characters long. And finally we our alert-box visible to the user.
  • Line 4: We start to operate on our ele element (which is our form “Full name” input). First we remove class“normal”, which may be there from previous validation, then we apply class “wrong” to it.
  • Line 5: If the name user typed in was long enough, then…
  • Line 6: We start to operate on our nameInfo element. We remove class “error” if it’s there, and apply class“correct”. We put  inside to let the user know it’s all good. We show the alert-box (if it wasn’t visible before).
  • Line 7: We start to operate on our ele element. We remove class “wrong” if it’s there, and apply class“normal”.

Well done! This is our first validation method. Now it’s time to test it, but before we can do that, we need to write few more lines of code.

We need to make sure, that our fullName method will be called when the user finished filling out the “Full name” field. To achieve that, we need to bind our method to certain user action. There are two great jQuery functions that would serve that purpose well: blur() and change(). We are going to use change().

Paste this code below the whole jVal object:

1 $('#fullname').change(jVal.fullName);

What it does in human words: if the user changes value of the “Full name” field and then leaves (e.g. to fill out another field), our fullName method is fired up, to validate “Full name” field.

Right now you should have one fully working validation method, so test it. Your whole validate.js file should like like this:

1 $(document).ready(function(){
2
3     var jVal = {
4         'fullName' function() {
5
6             $('body').append('<div id="nameInfo"></div>');
7
8             var nameInfo = $('#nameInfo');
9             var ele = $('#fullname');
10             var pos = ele.offset();
11
12             nameInfo.css({
13                 top: pos.top-3,
14                 left: pos.left+ele.width()+15
15             });
16
17             if(ele.val().length < 6) {
18                 jVal.errors = true;
19                     nameInfo.removeClass('correct').addClass('error').html('&larr; at least 6 characters').show();
20                     ele.removeClass('normal').addClass('wrong');
21             else {
22                     nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
23                     ele.removeClass('wrong').addClass('normal');
24             }
25         }
26     };
27
28     // bind jVal.fullName function to "Full name" form field
29     $('#fullname').change(jVal.fullName);
30
31 });

Step 5: Validating User’s Date of Birth

Starting from now, it will all get easier. Our validation methods are in 90% the same, so all you have to do is copy our fullName method, and only apply some changes

Great, so now just copy whole fullName method, paste it below and rename it to birthDate. The changes we need to make are:

  • all nameInfo occurences have to become birthInfo
  • instead of #fullname, assign #birthday element to variable ele
  • add this regular expression pattern below the whole birthInfo.css() declaration:
    1 var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;
  • our previous if() statement has to become:
    1 if(!patt.test(ele.val()))
  • validation message has to become ← type in date in correct format

This is how birthDate method should look like after these changes:

1 'birthDate' function (){
2
3     $('body').append('<div id="birthInfo"></div>');
4
5     var birthInfo = $('#birthInfo');
6     var ele = $('#birthday');
7     var pos = ele.offset();
8
9     birthInfo.css({
10         top: pos.top-3,
11         left: pos.left+ele.width()+15
12     });
13
14     var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;
15
16     if(!patt.test(ele.val())) {
17         jVal.errors = true;
18             birthInfo.removeClass('correct').addClass('error').html('&larr; type in date in correct format').show();
19             ele.removeClass('normal').addClass('wrong');
20     else {
21             birthInfo.removeClass('error').addClass('correct').html('&radic;').show();
22             ele.removeClass('wrong').addClass('normal');
23     }
24 }
  • Line 14: It’s a regular expression pattern. It’s not our main focus in this tut, so let me just explain it very roughly. This pattern decides how the date format should look like, in this case it’s: two digits followed byhyphen then again two digits followed by hyphen and finally four digits at the end. So, the pattern applies for example to this date: 28-03-1987.
  • Line 16: We’re checking if date that user typed in conforms to our pattern from above.

And of course, we need to bind this birthDate method to the “Date of birth” form field. It’s the same thing we did with fullName before, only with different names. Paste it at the bottom (outside of the jVal object), below our fullName binding declaration:

1 $('#birthday').change(jVal.birthDate);

And we have another fully working validation method. Great job!

Step 6: Validating User’s Gender

Again, simply copy the whole fullName method, rename it to gender and apply these changes:

  • all nameInfo occurences have to become genderInfo
  • instead of #fullname, assign #woman element to variable ele
  • in genderInfo.css() declaration, the top value has to become top: pos.top-10 and the left value has to become left: pos.left+ele.width()+60
  • our previous if() statement has to become:
    1 if($('input[name="gender"]:checked').length === 0)
  • validation message has to become ← are you a man or a woman?

This is how gender method should look like after these changes:

1 'gender' function (){
2
3     $('body').append('<div id="genderInfo"></div>');
4
5     var genderInfo = $('#genderInfo');
6     var ele = $('#woman');
7     var pos = ele.offset();
8
9     genderInfo.css({
10         top: pos.top-10,
11         left: pos.left+ele.width()+60
12     });
13
14     if($('input[name="gender"]:checked').length === 0) {
15         jVal.errors = true;
16             genderInfo.removeClass('correct').addClass('error').html('&larr; are you a man or a woman?').show();
17             ele.removeClass('normal').addClass('wrong');
18     else {
19             genderInfo..removeClass('error').addClass('correct').html('&radic;').show();
20             ele.removeClass('wrong').addClass('normal');
21     }
22 }
  • Line 14: We’re checking if user selected one of two radio buttons. $('input[name="gender"]:checked')selects all inputs with name “gender” (in this case all radio buttons) that are checked. Than we check if the number of selected radios (.length) equals 0, which would mean that user didn’t select any.

As always, we have to bind this gender method to our “Gender” radio buttons:

1 $('input[name="gender"]').change(jVal.gender);

There, another validation method completed. Three more to go :).

Step 7: Validating Vehicles Owned by User

This time copy gender method, rename it to vehicle and apply following changes:

  • all genderInfo occurences have to become vehicleInfo
  • instead of #woman, assign #ship element to variable ele
  • in vehicleInfo.css() declaration, the left value has to become left: pos.left+ele.width()+40
  • our previous if() statement has to become:
    1 if($('input[name="vehicle"]:checked').length <= 1)
  • validation message has to become ← I am sure you have at least two!

This is how vehicle method should look like after these changes:

1 'vehicle' function (){
2
3     $('body').append('<div id="vehicleInfo"></div>');
4
5     var vehicleInfo = $('#vehicleInfo');
6     var ele = $('#ship');
7     var pos = ele.offset();
8
9     vehicleInfo.css({
10         top: pos.top-10,
11         left: pos.left+ele.width()+40
12     });
13
14     if($('input[name="vehicle"]:checked').length <= 1) {
15         jVal.errors = true;
16             vehicleInfo.removeClass('correct').addClass('error').html('&larr; I am sure you have at least two!').show();
17             ele.removeClass('normal').addClass('wrong');
18     else {
19             vehicleInfo.removeClass('error').addClass('correct').html('&radic;').show();
20             ele.removeClass('wrong').addClass('normal');
21     }
22 }
  • Line 14: Weíre checking if user selected two or more checkboxes. $('input[name="vehicle"]:checked')selects all inputs with name ìvehicleî (in this case all checkbox buttons) that are checked. Than we check if the number of selected checkboxes (.length method) equals or is less than 1, which would mean that user didnít select any checkboxes or selected only one.

Again, we have to bind this vehicle method to our “Vehicle” checkboxes:

1 $('input[name="vehicle"]').change(jVal.vehicle);

Tired? We have couple more methods to cover :). Time for email validation.

Step 8: Validating User’s Email Adress

This time, copy our birthDate method, rename it to email and apply these changes:

  • all birthInfo occurences have to become emailInfo
  • instead of #birthday, assign #email element to variable ele
  • our previous regular expression pattern has to become:
    1 var patt = /^.+@.+[.].{2,}$/i;
  • validation message has to become ← give me a valid email adress, ok?

This is how email method should look like after these changes:

1 'email' function() {
2
3     $('body').append('
<div id="emailInfo”>

');

4
5     var emailInfo = $('#emailInfo');
6     var ele = $('#email');
7     var pos = ele.offset();
8
9     emailInfo.css({
10         top: pos.top-3,
11         left: pos.left+ele.width()+15
12     });
13
14     var patt = /^.+@.+[.].{2,}$/i;
15
16     if(!patt.test(ele.val())) {
17         jVal.errors = true;
18             emailInfo.removeClass('correct').addClass('error').html('&larr; give me a valid email adress, ok?').show();
19             ele.removeClass('normal').addClass('wrong');
20     else {
21             emailInfo.removeClass('error').addClass('correct').html('&radic;').show();
22             ele.removeClass('wrong').addClass('normal');
23     }
24 }
  • Line 14:For this tutorial I decided to go with very simple, almost basic regular expression pattern for email adress: one or more characters followed by smbol, then again one or more characters followed by .period, and at the end there should be two or more characters. So, the pattern applies to this email adress example: mickey@mou.se

Of course, bind this .email method to our “Email” form field:

1 $('#email').change(jVal.email);

Time for the last of our validation methods: about.

Step 9: Validating User’s About Info

For this last method, copy fullName, rename it to about and apply following changes:

  • all nameInfo occurences have to become aboutInfo
  • instead of #fullname, assign #about element to variable ele
  • our previous if() statement has to become:
    1 if(ele.val().length < 75)
  • validation message has to become ← come on, tell me a little bit more!

This is how our about method should look like after these changes:

1 'about' function() {
2
3     $('body').append('
<div id="aboutInfo”>

');

4
5     var aboutInfo = $('#aboutInfo');
6     var ele = $('#about');
7     var pos = ele.offset();
8
9     aboutInfo.css({
10         top: pos.top-3,
11         left: pos.left+ele.width()+15
12     });
13
14     if(ele.val().length < 75) {
15         jVal.errors = true;
16             aboutInfo.removeClass('correct').addClass('error').html('&larr; come on, tell me a little bit more!').show();
17             ele.removeClass('normal').addClass('wrong').css({'font-weight''normal'});
18     else {
19             aboutInfo.removeClass('error').addClass('correct').html('&radic;').show();
20             ele.removeClass('wrong').addClass('normal');
21     }
22 }

And of course we need to bind it to our “About” form field:

1 $('#about').change(jVal.about);

This is it! We just completed all our validation methods. It’s almost like they say: the end is nigh! There’s only two things left to do:

  • build our last sendIt method
  • manage properly the submit action of the submit button

Step 10: Final sendIt Method

This method will be called after all our validation methods, as the last one, after clicking on the “submit” button. It will check if no errors occurred during validation (while performing any of our validation methods) up until the moment it’s called. The good news is, it couldn’t be more simple:

1 'sendIt' function (){
2     if(!jVal.errors) {
3         $('#jform').submit();
4     }
  • Line 2: Remember that errors variable I told you we’re going to use later? Well, this “later” is right now :). If even one little error occurred during the validation, this errors variable was set to true. In human words it actually means something like: “yes, it’s true that we got some errors during validation”. So here we’re checking if it’s actually NOT true, which equals to no errors from validation.
  • Line 3: If there were no errors, just finally submit the whole form.

Step 11: Managing User’s Submit Action

The only thing left now, is to manage what happens when the user clicks on our “submit” button. And it goes like this:

1 $('#send').click(function (){
2     var obj = $.browser.webkit ? $('body') : $('html');
3     obj.animate({ scrollTop: $('#jform').offset().top }, 750, function (){
4         jVal.errors = false;
5         jVal.fullName();
6         jVal.birthDate();
7         jVal.gender();
8         jVal.vehicle();
9         jVal.email();
10         jVal.about();
11         jVal.sendIt();
12     });
13     return false;
14 });
  • Line 1: We grab the send element, which is the “submit” button in our form, and if someone clicks on it we perform all code below.
  • Line 2: The thing is: when you want to apply scrolling to browser window, different browsers will work with different elements. And so: Chrome and Safari will work with body. Internet Explorer and Firefox will work withhtml. Opera will work with both. Unfortunately in our case we can’t just use $('html, body') to target both these elements (I’ll talk about that another time). So we need to somehow decide which of these elements we should apply scrolling to. And this is where jQuery comes with help. It provides us with $.browser property – it allows us to detect which browser we are working in. By using $.browser.webkit we’re just checking if our browser is running on webkit engine; if so then we assign body element to the obj variable we just created, if not we assign html element to it. Important noteIt should be avoided and it’s considered bad practice to perform any kind of “browser detection”, you should use “feature detection” instead. But we can get away with that for our learning purposes.
  • Line 3:We apply scrollTop animation to our obj element. The point that scrolling should stop is the beginning of the form, which is determined by accessing top value of its position in the document, which we get thanks to jQueryoffset() function. Next we say that this scrolling animation should last 750 milliseconds, and when it’s done we…
  • Line 4: Set variable jVal.errors to false, to clear errors that might occurred in previous validation, and then we…
  • Lines 5-11: Call all our validation methods one by one, with sendIt method at the end, which will check if there were no errors and submit the whole form if so.
  • Line 13:We return false to that click event of the “submit” button in our form, which means that the form won’t be submitted right away, the script will perform actions planned by us first.

Final Product

Right now our validation script is fully completed and should look like this:

1 $(document).ready(function(){
2
3     var jVal = {
4         'fullName' function() {
5
6             $('body').append('<div id="nameInfo"></div>');
7
8             var nameInfo = $('#nameInfo');
9             var ele = $('#fullname');
10             var pos = ele.offset();
11
12             nameInfo.css({
13                 top: pos.top-3,
14                 left: pos.left+ele.width()+15
15             });
16
17             if(ele.val().length < 6) {
18                 jVal.errors = true;
19                     nameInfo.removeClass('correct').addClass('error').html('&larr; at least 6 characters').show();
20                     ele.removeClass('normal').addClass('wrong');
21             else {
22                     nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
23                     ele.removeClass('wrong').addClass('normal');
24             }
25         },
26
27         'birthDate' function (){
28
29             $('body').append('<div id="birthInfo"></div>');
30
31             var birthInfo = $('#birthInfo');
32             var ele = $('#birthday');
33             var pos = ele.offset();
34
35             birthInfo.css({
36                 top: pos.top-3,
37                 left: pos.left+ele.width()+15
38             });
39
40             var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;
41
42             if(!patt.test(ele.val())) {
43                 jVal.errors = true;
44                     birthInfo.removeClass('correct').addClass('error').html('&larr; type in date in correct format').show();
45                     ele.removeClass('normal').addClass('wrong');
46             else {
47                     birthInfo.removeClass('error').addClass('correct').html('&radic;').show();
48                     ele.removeClass('wrong').addClass('normal');
49             }
50         },
51
52         'gender' function (){
53
54             $('body').append('<div id="genderInfo"></div>');
55
56             var genderInfo = $('#genderInfo');
57             var ele = $('#woman');
58             var pos = ele.offset();
59
60             genderInfo.css({
61                 top: pos.top-10,
62                 left: pos.left+ele.width()+60
63             });
64
65             if($('input[name="gender"]:checked').length === 0) {
66                 jVal.errors = true;
67                     genderInfo.removeClass('correct').addClass('error').html('&larr; are you a man or a woman?').show();
68                     ele.removeClass('normal').addClass('wrong');
69             else {
70                     genderInfo.removeClass('error').addClass('correct').html('&radic;').show();
71                     ele.removeClass('wrong').addClass('normal');
72             }
73         },
74
75         'vehicle' function (){
76
77             $('body').append('<div id="vehicleInfo"></div>');
78
79             var vehicleInfo = $('#vehicleInfo');
80             var ele = $('#ship');
81             var pos = ele.offset();
82
83             vehicleInfo.css({
84                 top: pos.top-10,
85                 left: pos.left+ele.width()+40
86             });
87
88             if($('input[name="vehicle"]:checked').length <= 1) {
89                 jVal.errors = true;
90                     vehicleInfo.removeClass('correct').addClass('error').html('&larr; I\'m sure you have at least two!').show();
91                     ele.removeClass('normal').addClass('wrong');
92             else {
93                     vehicleInfo.removeClass('error').addClass('correct').html('&radic;').show();
94                     ele.removeClass('wrong').addClass('normal');
95             }
96         },
97
98         'email' function() {
99
100             $('body').append('<div id="emailInfo"></div>');
101
102             var emailInfo = $('#emailInfo');
103             var ele = $('#email');
104             var pos = ele.offset();
105
106             emailInfo.css({
107                 top: pos.top-3,
108                 left: pos.left+ele.width()+15
109             });
110
111             var patt = /^.+@.+[.].{2,}$/i;
112
113             if(!patt.test(ele.val())) {
114                 jVal.errors = true;
115                     emailInfo.removeClass('correct').addClass('error').html('&larr; give me a valid email adress, ok?').show();
116                     ele.removeClass('normal').addClass('wrong');
117             else {
118                     emailInfo.removeClass('error').addClass('correct').html('&radic;').show();
119                     ele.removeClass('wrong').addClass('normal');
120             }
121         },
122
123         'about' function() {
124
125             $('body').append('<div id="aboutInfo"></div>');
126
127             var aboutInfo = $('#aboutInfo');
128             var ele = $('#about');
129             var pos = ele.offset();
130
131             aboutInfo.css({
132                 top: pos.top-3,
133                 left: pos.left+ele.width()+15
134             });
135
136             if(ele.val().length < 75) {
137                 jVal.errors = true;
138                     aboutInfo.removeClass('correct').addClass('error').html('&larr; come on, tell me a little bit more!').show();
139                     ele.removeClass('normal').addClass('wrong').css({'font-weight''normal'});
140             else {
141                     aboutInfo.removeClass('error').addClass('correct').html('&radic;').show();
142                     ele.removeClass('wrong').addClass('normal');
143             }
144         },
145
146         'sendIt' function (){
147             if(!jVal.errors) {
148                 $('#jform').submit();
149             }
150         }
151     };
152
153 // ====================================================== //
154
155     $('#send').click(function (){
156         var obj = $.browser.webkit ? $('body') : $('html');
157         obj.animate({ scrollTop: $('#jform').offset().top }, 750, function (){
158             jVal.errors = false;
159             jVal.fullName();
160             jVal.birthDate();
161             jVal.gender();
162             jVal.vehicle();
163             jVal.email();
164             jVal.about();
165             jVal.sendIt();
166         });
167         return false;
168     });
169
170     $('#fullname').change(jVal.fullName);
171     $('#birthday').change(jVal.birthDate);
172     $('input[name="gender"]').change(jVal.gender);
173     $('input[name="vehicle"]').change(jVal.vehicle);
174     $('#email').change(jVal.email);
175     $('#about').change(jVal.about);
176
177 });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s