This tutorial will show you how to validate a simple contact form using the bassistance jQuery validation plugin. This will allow you to validate a form before it has been submitted. See the demo here.
Step 1 – The Form
This same form was featured on the Ajax Contact Form Tutorial. So if you want to extend the original form, this tutorial should enable you to do so quite easily.
To start off we need a new file, we will call it contact.html, in it we will create our form like so.
<form id="contactForm" method="" action="">
<label for="name">Name </label>
<input id="name" name="name" />
<label for="email">E-Mail </label>
<input id="email" name="email" />
<label for="message">Your Message </label>
<textarea id="message" name="message" rows="4" cols="30" >
<input class="submit" type="submit" value="submit"/>
Now we have a simple form with 2 fields and a text box, which we will validate.
Step 2 – The Plugin
The plugin we are using can be downloaded from here, we will also need a copy of jQuery, which can be dowloaded from here. Now that we have the files we need to attach them to our contact.html file like so.
Please note that Its very important that you call jQuery in first otherwise the framework will not work.
Step 3 – The Code
The code itself is very light weight, check it out
//initiate validator on load
// validate contact form on keyup and submit
//set the rules for the field names
//set messages to appear inline
name: "Please enter your name",
email: "Please enter a valid email address",
message: "Please enter your message"
All we are doing here is calling an onload function, which initiates the validation of the form using validate. The validate plugin requires you pass through a few paramenters.
rules – allows you to specify the field names you wish to act upon, in our case we have used name, email and message. Inside of this we are specifying if the the field is required or not, by passing either true or false, we want to validate all fields, so all are marked as true. The next parameter is minlength, which ..you guessed it, allows you to set a minimum number of characters to be entered.
message – allows you to set a specific message for a particular field, if you choose not to set a messge, a default one is provided which will say something like “this field is required”
Step 4 – Tidy It Up
To make the warning messages appear more noticeable we can add some styling, although this is not imperative. You may notice that when an error message appears its wrapped in a class called error making it simple for us to add some style information like so
font: 12pt verdana;
And thats all there is to it. Download the code and try for yourself here