cameras in the cloud

this is our weblog. it includes ramblings on the latest in home and business video monitoring, cool gadgets for the home, cloud and mobile technologies, web development, along with other random topics.

11
Feb

jQuery Form Validation Using onblur and onfocus

Posted by on in Web Development
  • Font size: Larger Smaller
  • 5 Comments

In a previous post I created a jQuery Form Validation Tutorial. Today I wanted to give a quick discussion on how to use jQuery validation with onblur or onfocus.

Have you ever seen a form where there is some help text available inside a text box:

b2ap3_thumbnail_blog-jquery-val.JPG

It gives a visual for users to know what they need to add to that particular text box. As soon as someone clicks on the box the text disappears and someone can go ahead and start typing away. This is a very common technique you see used in many forms today. Disclaimer: This is old school. There is a better way with "placeholder" in HTML5 but if you want it to work across some older browsers then this is still a good choice.

Let's take a look at the HTML code first:

<form method='post' action=''>
    <label for="Name">Name:&nbsp;</label>
    <input id="Name" name="a_name" value="Enter a name" onfocus="if(this.value==this.defaultValue){this.value='';}" onblur="if(this.value==''){this.value=this.defaultValue;}" />
    <button type='submit' class='submit_name' name='addname' value='Add'>Add</button>
</form>

Notice the JavaScript for the onfocus and onblur attributes. This mimics the behavior to show the text then remove it once the users clicks in the area. Naturally you want to use jQuery validation on this text box. So you go ahead and add all kinds of great things like checking the length of the string, making sure there is a minimum, etc.

$("#aform").validate({
        rules: {
            a_name: {
                minlength: 3,
                maxlength: 32
            }
        },         messages: {             a_name: {                 minlength: "At least 3 characters required!",                 maxlength: "Maximum 32 characters allowed!"
            }         }     });

Don't forget to add jquery.validate.js and Bob's your uncle. Well...except for one problem, what if someone doesn't enter anything into that box? You will get a string submitted with "Enter a name". Obviously not what we want.

To fix this we could try to check the input field and clear it out if it equals the default value before calling validate or we can use jQuery validation for this. Since that's what we are here for let's show you what that would look like:

var enterText =  $("#Name")[0].defaultValue; // "Enter a name";
$.validator.addMethod("testvalidation", function(value, element) {
      return value != enterText && value.length > 0;
  }, "You still need to enter a name");
$("#aform").validate({
          rules: {
              a_name: {
                  testvalidation: true,
                  minlength: 3,
                  maxlength: 32
              }
        },
          messages: {
              a_name: {
                  minlength: "At least 3 characters required!",
                  maxlength: "Maximum 32 characters allowed!"
              }
          }
    });

What we have done here is use jQuery's custom validation method called "addMethod". Once we grab the value on line #1 with "enterText" it is just a matter of checking if it exists. Simple, right?

Here is a jsFiddle to play with the code.

Entrepreneur and Camcloud founder. I'm a 12+ year tech veteran. Former Director of Product Management and Certified Scrum Product Owner (CSPO). I focus on front-end web development with jQuery, HTML5 & cloud infrastructure.


Find me on Twitter

Comments

  • Guest
    vsync Wednesday, 13 February 2013

    you should check out my validator plugin, which is insanely good:

    http://dropthebit.com/150/validation-styling-semantics-of-forms/

  • Guest
    Andy Tuesday, 19 February 2013

    Thanks for the update of your tutorial. This is just what I needed today. Could you make your javascript unobtrusive for onfocus() and onblur() event handlers?

  • alen
    alen Tuesday, 19 February 2013

    Hi Andy,
    In terms of progressive enhancement going with the HTML5 "placeholder" is a better option. This tutorial is just a good example of using jQuery custom validation.

  • Guest
    john Sunday, 04 May 2014

    nice update to the previous example of form validations

  • Guest
    fxcg Tuesday, 09 September 2014

    gbf

Leave your comment

Guest Saturday, 25 October 2014
Security

We take your security and privacy seriously. Be sure to select a strong password for your account. Read our privacy policy for more information. 
Contact

1-855-519-1530
sales@camcloud.com
support@camcloud.com