Simple form validation using jQuery

  • Posted on: 23 April 2011
  • By: Antti

I needed an easy way to do validation for a custom HTML form. Since the website was in Drupal which uses jQuery it was natural to look for solutions that take advantage of that library. I ended up using the jQuery Validation plugin which is simple to implement on any form.

The setup

A rather plain looking newsletter sign-up form with the name and email address as required fields.

Form HTML

<form action="#" method="post" id="signup_form">
 <fieldset>
 <legend>Newsletter sign-up</legend>
  <p>
   <label for="name">Name <span>*</span></label>
   <input type="text" name="name"size="30" />
  </p>
  <p>
   <label for="email">Email <span>*</span></label>
   <input type="text" name="email" size="30" /></p>
  <p>
  <p>
   <label for="company">Company</label>
   <input type="text" name="company" size="30" />
  </p>
   <label for="phone">Phone</label>
   <input type="text" name="phone" size="15" />
  </p>
  <p>
   <input type="submit" value="Submit" name="submit" />
  </p>
 </fieldset>
</form>

Form CSS

#signup_form fieldset {
 padding:1em 1.5em;
 border:1px solid #bbb;
}

#signup_form legend {
 font-weight:bold;
}

#signup_form label {
 display:block;
}

#signup_form label span {
 color:#f00;
}

Form output

Sign-up form

Validating the form

In order to make it work you need the following:

Link it up

Either copy the scripts to your own server or hotlink via a CDN. You also need to initiate the validation to your specified form. Replace the signup_form with whatever your form ID is.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#signup_form").validate();
});
</script>

Class it up

Next up you add specific classes to your form fields depending on how you want them validated. Have a look at the available validation methods. I set the name and email fields as required and the email field to conform to a valid email address.

<p>
 <label for="name">Name <span>*</span></label>
 <input type="text" name="name"size="30" class="required" />
</p>
<p>
 <label for="email">Email <span>*</span></label>
 <input type="text" name="email" size="30" class="required email" /></p>
<p>

Test and polish

The validation should now be working as expected. To make the error messages appear a bit nicer and more obvious you can style it with CSS.

#signup_form .error {
 padding:5px;
 margin:5px 0;
 border:1px solid #f00;
}

The final output when testing is looking like this:

Sign-up form with validation

And there we have it. A robust form validation using jQuery with just a few simple steps!

View Demo