Wednesday, July 29, 2009

Fun with jQuery Form Validate Plugin

Things to know about the jQuery form validation plugin

1. When dealing with input text you just need to add 'class' => 'required' to
<input type="text" 'class' => 'required' name="username"/>

2. Then add this line to get the form to validate
$().ready(function() {

3. What to do about checkboxes and how to position your error messages:

The form validate will auto insert your error messages when dealing with text fields and other input types. However when you're validating across multiple items like a checkbox you often want to position the error message in in a specific area.

<input type="text"><label class="error"> // Is fine

<input type="checkbox" name="data[]" value="1"><label class="error">
<input type="checkbox" name="data[]" value="1">

// The above error is out of place.

We can specify a label and use the for attribute to state where we want the error message to always show up.

<label class="error" for="data[]" >Pleased select at least two types of spam.</label> // insert this code anywhere on the page where you want the error message to appear

The problem arises when we
i) label.error { display: block; } // This causes the above label to always appear on first load of the page cause it's not hidden. Other inputs are fine as the validate 'auto-inserts' the errors.

ii) label.error { display: none; } // Next we try this style to make the explicit label.error disappear on first page load, but a side effect occurs. This style is inserted into ALL label.errors

style="display: inline"

Every label.error now loses their block style and we have a formatting problem


<label for="data[]" class="error" style="display: none !important; clear: both; padding-bottom: 5px;">Pleased select at least two types of spam.</label> // This causes the label to be displayed hidden on the first load, and puts it on a new line cause of the clear: both;

2) OR wrap the label in a
<div class="errorCheckBoxBox"><label for="data[]" class="error"></label></div>

with the style
.errorCheckBox label{
display: none;

A better solution as it doesn't need additional style tags.

No comments: