jQuery Form Validation Using onblur and onfocus

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:


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:


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.


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:


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.

If you’re looking for a surveillance camera cloud storage service, try out Camcloud’s free plan! We also have several paid plans that offer a large amount of cloud storage.

No comments yet.