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.

05
Dec

jQuery Form Validation Tutorial

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

There are lots of ways to perform validation on your html forms but nothing is easier than using jQuery’s validation plug-in. I’ll take you through a small tutorial to help you understand how to make it work. Let’s take a look at what you can do and how you can customize the built in validation.

Of course as always make sure you reference the main site here along with all the available validation methods found here. There are also a few good tutorials like this one and especially this one, but I wanted to take the layman's approach right from the beginning. Let’s go into details of what is needed using a simple HTML form example. 

As part of this tutorial I'll take you through these items:

  1. Use HTML and CSS for jQuery validation
  2. Use jQuery to define your own validation rules
  3. Define more rules with custom messages
  4. Create your own custom jQuery validation method


First let's start with the very simplest form using HTML/CSS:

<head>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script>
$(function() {
   $( "#mytestform" ).validate();
});
</script>
</head>
<body>
<form id="mytestform" name="" method="get"  action="">
                  <p>
                   <label for="aname">Name:&nbsp;</label>
                  <input name="aname" class="required" minlength=”4” size="20" />
                   </p>
                   <p>
                  <label for="food">Do you like Italian food:&nbsp;</label>
                  <select id="italianstatus" name="italian_food">
                          <option value="yes" selected="selected">Hell Yes!</option>
                          <option value="no">Makes me wanna puke</option>
                          <option value="sometimes">Just on Monday</option>
                  </select>
                  <input class="submit" type="submit" value="Submit"/>
                   </p>
   </form>

</body>

The key here is the the input field for the name has “minlength” and “required”. This will either trigger an empty name or give you the message if the length of characters is smaller than 4.



It is easy as that. One line of jQuery code. For more details on the attributes you can use see Raymond’s blog. First thing that jumps out is that the styling is butt ugly. Just add a little color and positioning and you are set.

<style type="text/css">
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
</style>




Okay but how about defining those rules in jQuery for more customization? Simple, add to your validation routine and remove the “minlength”/”required” attributes from the HTML:

<head>
<meta charset="utf-8" />
<style type="text/css">
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script>
$(function() {
   $( "#mytestform" ).validate({
           rules: {
                   aname: "required"
           }
   });
});
</script>
</head>
<body>
<form id="mytestform" name="" method="get"  action="">
                  <p>
                   <label for="aname">Name:&nbsp;</label>
                  <input name="aname" size="20" />
                   </p>
                   <p>
                  <label for="food">Do you like Italian food:&nbsp;</label>
                  <select id="italianstatus" name="italian_food">
                          <option value="yes" selected="selected">Hell Yes!</option>
                          <option value="no">Makes me wanna puke</option>
                          <option value="sometimes">Just on Monday</option>
                  </select>
                  <input class="submit" type="submit" value="Submit"/>
                   </p>
   </form>

</body>


Let’s keep on building on this. Let’s add a bunch of new criteria such as minimum/maximum length and even custom messages. Nothing changes with the HTML or libraries so here is the changes to the jQuery code:

<script>
$(function() {
   $( "#mytestform" ).validate({
           rules: {
                   aname: {
                           required: true,
                           minlength: 4,
                           maxlength: 20
                   }
           },
           messages: {
                   aname: {
                           required: "Dude, enter a name",
                           minlength: $.format("Keep typing, at least {0} characters required!"),
                           maxlength: $.format("Whoa! Maximum {0} characters allowed!")
                   }
           }
   });
});
</script>


You can see that I’ve added a few more criteria along with the custom messages. I’ve tied it all to the name in the form “aname”. For the other fields in your form just add to this depending on the name. I’ve also introduced the format method in the message. This lets us replace the argument given for minlength and maxlength. Handy to know that we don’t have to worry about hard-coding that value if they ever change.

To finish it up, lets add a custom validation routine. Again easy with the plugin. This is where the plugin’s addMethod comes into play.

<script>
$(function() {
   $( "#mytestform" ).validate({
           rules: {
                   aname: {
                           required: true,
                           minlength: 4,
                           maxlength: 20,
                           customvalidation: true
                   }
           },
           messages: {
                   aname: {
                           required: "Dude, enter a name",
                           minlength: $.format("Keep typing, at least {0} characters required!"),
                           maxlength: $.format("Whoa! Maximum {0} characters allowed!")
                   }
           }
   });
   $.validator.addMethod("customvalidation",
           function(value, element) {
                   return /^[A-Za-z\d=#$%@_ -]+$/.test(value);
           },
   "Sorry, no special characters allowed"
   );
});
</script>


This is a regex example to test for special characters. Here I’m allowing some special characters but others I’m not. So if you enter “*” or “!” for example, you will get the message. Pretty cool huh?

These are the steps I went through to understand this plugin. I’m certainly not an expert (far from it) so comments are most welcome. I hope this can help you on your way.

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
    Javad Tuesday, 25 December 2012

    nice

  • Guest
    Naresh Tuesday, 09 April 2013

    Hi put submit button before closing tag of the form.

  • alen
    alen Tuesday, 09 April 2013

    Uh ya, thanks. Surprised no one noticed that before. This is fixed.

  • Guest
    Android Saturday, 05 January 2013

    Shame On You For Bore Tutorial

  • Guest
    V Friday, 21 June 2013

    Dude. Get a life. Pity you for the rot you go through.

    Instead of bad-mouthing somebody whose trying to contribute & spread the knowledge, try contributing something of your own.
    Agreed the tutorial is for beginners. But, nonetheless there will be many who find it useful.

    Good job Alen.

    As of you @Android, try and find peace.

  • Guest
    Robert Wednesday, 19 February 2014

    I agree. @Android Loser.

  • Guest
    Sufiyan Monday, 07 January 2013

    Hey, Thanks a lot for such a useful tutorial, i am beginner and understood your tutorial clearly.

  • Guest
    Durgaprasad Tuesday, 22 January 2013

    Hey, Thanks a lot this tutorial very useful for me.

  • Guest
    Abhi Wednesday, 23 January 2013

    Hey thanx for this tutorial... i needed tutorial like this.

  • Guest
    Piyush Monday, 28 January 2013

    different error text for different element and addMethod you can find a nice example here
    http://www.thewebexpert.in/jquery-vidation-js-tutorial/

  • Guest
    monja Thursday, 21 March 2013

    Thanks, Alen, for a nice and true tutorial.

    In comparison, this (http://www.thewebexpert.in/jquery-vidation-js-tutorial/) however is better described here as an *example*, and certainly *not* a tutorial as its claims in its website; unless the website would post it as an example of what a tutorial should be not.

  • Guest
    Barney Friday, 01 February 2013

    Great tutorial. Very Helpful

  • Guest
    Ghanshyam Friday, 08 February 2013

    nice one... easy to understand sir....

  • Guest
    Venkatesh Friday, 15 February 2013

    Very nice is useful to understand for me

  • Guest
    Frank Monday, 18 February 2013

    Thanks, ideal for my prototypes.

  • Guest
    Andy Tuesday, 19 February 2013

    Thanks for taking the time to post. You are using "name" attribute twice in your input:



    Is there a reason for using two?

  • alen
    alen Tuesday, 19 February 2013

    Andy,

    Ack! Thanks for catching that, it shouldn't be there. I've updated the post.

  • Guest
    Ram Krishna Dhakad Wednesday, 27 February 2013

    thank you.i was in need of this type of tutorial.

  • Guest
    aristos Thursday, 28 February 2013

    thanks man. Amazing tutorial!!!

  • Guest
    Karen Thursday, 28 February 2013

    Thank you. This was wonderful, it was a gift to write it up and post it for us! Gracias!

Leave your comment

Guest Thursday, 27 November 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