Note: jQuery form validation is not an alternative to server-side form validation. It will not make sure that an email address or credit card number is truly valid; it will, however, make sure that visitors fill out required form fields and that they enter a correctly-formatted email address.
In this example, we will set up the form with the following fields: First name, last name, phone number, email, city, state, and a message area. We will make the first and last names and the email address required fields, as well as require that the email address be formatted correctly. Your form should end up looking something like this:
<form id="theform" method="post"> <label for="firstName">Your First Name</label> <input class="required" name="firstname" type="text" id="firstName"> <label for="lastName">Your Last Name</label> <input class="required" name="lastName" type="text" id="lastName" > <label for="phone">Your Phone Number</label> <input name="phone" type="text" id="phone"> <label for="email">Email</label> <input class="required email" name="email" type="text" id="email"> <label for="city">City</label> <input name="city" type="text" id="city"> <label for="state">State</label> <input name="state" type="text" id="state"> <label>Your Message</label> <textarea name="comments" rows="5" style="width:535px"></textarea> <input class="button" type="submit" value="SEND CONTACT FORM" /> </form>
There are a couple of very important point to note for this tutorial: 1) Make sure to include
id="theform" in your
<form> tag, and; 2) Any form field that is required needs to have
class="required" in its
<input> tag. The email field needs to have
For those of you unfamiliar with jQuery, all you really need to know about it for this tutorial is that you have to include the jQuery library whenever you want to use it, and that there are also (usually) additional files you need to point to for each plugin to work. In this instance, all we need are the jQuery library and the "validate" plugin. While you can download these files, push them up to your web server, and point to them in your HTML, it is just as easy to point to trusted servers where the files always live. So that's what we'll do. Insert the two following tags into the
<head> of your contact form page:
It's pretty safe to say that Google and Microsoft aren't going away anytime soon, so you can point to their servers for all your jQuery needs or, if you're not comfortable with that, just put the files on your server and point to them instead.
<head> of your page, just beneath the
<script> tags that point to jQuery: