Online Book Reader

Home Category

JQuery_ Novice to Ninja - Earle Castledine [96]

By Root 1054 0
a checkbox or radio button. For example, you can check to see if a box is checked with if($(this).is(':checked')).

After you’ve selected your elements, it’s time to find their values so you can validate them against your requirements. We’ve already used the val function enough to know what it does: it returns the value of a form field. We can now perform some simple validation—let’s test to see if any text boxes in a form are empty:

chapter_07/01_simple_validation/script.js (excerpt)

$(':submit').click(function(e) {

$(':text').each(function() {

if ($(this).val().length == 0) {

$(this).css('border', '2px solid red');

}

});

e.preventDefault();

});


Fill out one or two of the text inputs, and try submitting the form; any input you leave blank will be highlighted in red.

The val action works for select boxes and radio buttons too. As an example, let’s alert the radio button value when the user changes the selection:

chapter_07/02_radio_buttons/script.js (excerpt)

$(':radio[name=sex]').change(function() {

alert($(this).val());

});


This change event is fired whenever a value in a form has changed. For checkboxes, select boxes, and radio buttons, this occurs whenever the value changes from its current value. For a text input or textarea, it fires whenever a user changes the element’s value—but only when the focus is moved away from the element. This is a great way to implement some simple inline validation.

Let’s revisit our simple validation example, except that this time we’ll test for empty fields whenever the user moves to the next field. For this, we’ll need to capture the blur event, which fires whenever a form field loses focus. This is perfect for inline validation:

chapter_07/03_simple_inline_validation/script.js (excerpt)

$(':input').blur(function() {

if ($(this).val().length == 0) {

$(this)

.addClass('error')

.after('This field must … ');

}

});

$(':input').focus(function() {

$(this)

.removeClass('error')

.next('span')

.remove();

});


We’re just checking that the fields are filled in, but any type of validation can be implemented in this way. You can check for a minimum or maximum number of characters, or a specific format using regular expressions, or check that a password confirmation field matches the original password field.

Important: Avoid Over-validating!

One important point to consider when designing form validation: keep it simple! The more rules you add, the more likely you’ll have forgotten an edge case, and wind up frustrating some of your users. Offer hints, sample inputs, and guidance, instead of rules that will prevent users from submitting the form if their postal code is formatted differently to what you expected!

The submit Event

We also can hook into the submit event, which is fired when the form’s submitted. This is a better technique than listening for a click event on the submit button, as it will also fire if the user submits the form by pressing the Enter key. If you return false from the submit event handler, the form will not be submitted. In our example below, we’ll check all of the text boxes in the form. If any are left empty, we’ll pop up a message, and focus on the offending element:

chapter_07/04_submit_event/script.js (excerpt)

$("form").submit(function() {

var error = false;

$(this).find(":text").each(function() {

if ($(this).val().length == 0) {

alert("Textboxes must have a value!");

$(this).focus();

error = true;

return false; // Only exits the “each” loop

}

});

if (error) {

return false;

}

return true;

});


With all of these raw, form-based tools at your disposal you can easily add validation to your forms on a page-by-page basis. If you plan your forms carefully and develop a consistent naming standard, you can use jQuery to generalize your validation so that it can apply to many forms.

But—as we’ve already seen—there are an enormous number of edge cases to consider when designing form validation. If you need really bulletproof validation and would rather spend your time designing the user

Return Main Page Previous Page Next Page

®Online Book Reader