02.06.2013 Views

JavaScript & jQuery: The Missing Manual ... - Robert Guajardo

JavaScript & jQuery: The Missing Manual ... - Robert Guajardo

JavaScript & jQuery: The Missing Manual ... - Robert Guajardo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Form Validation<br />

$('#signup').validate({<br />

rules: {<br />

name: 'required'<br />

}<br />

}); // end validate()<br />

In this case, the field is named name, and the rule specifies that the field is required.<br />

To apply more than one validation rule to a form field, you must create another object<br />

for that field. For example, to expand the validation rules for the form in Figure<br />

9-6, you can add a rule that would not only make the email field required, but also<br />

specify that the email address must be validly formatted:<br />

1 $('#signup').validate({<br />

2 rules: {<br />

3 name: 'required',<br />

4 email: {<br />

5 required:true,<br />

6 email:true<br />

7 }<br />

8 }<br />

9 }); // end validate()<br />

Note: According to the rules of <strong>JavaScript</strong> object literals, you must end each name/value pair except the<br />

last one with a comma. For example, in line 3 above, name: ‘required’ must have a comma after it, because<br />

another rule (for the email field) follows it. Turn to page 145 for a refresher on how object literals work.<br />

Lines 4–7, shown in bold, specify the rules for the email field. <strong>The</strong> field’s name is<br />

email, as specified in the HTML (see the HTML code on page 285); required:true<br />

make the field required; and email:true makes sure the field contains an email address.<br />

You can use any of the validation types listed in Table 9-2. For example, say you add<br />

a field named birthday to the form used in this example. To ensure that a date is<br />

entered into the field, you can expand the list of rules like this:<br />

$('#signup').validate({<br />

rules: {<br />

name: 'required',<br />

email: {<br />

required:true,<br />

email:true<br />

},<br />

birthday: 'date'<br />

}<br />

}); // end validate()<br />

If you also want the birthday field to be required, adjust the code as follows:<br />

286 javascript & jquery: the missing manual<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!