jQuery Form Validation Using onblur and 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:
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.