11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Form Validation via Hidden Fields<br />

An even more elegant possibility is to use hidden form fields and (believe it or not) routines that<br />

are even more generic than those we just saw. For example, you might define pairs of fields<br />

like this:<br />

<br />

<br />

You would define hidden form fields for each entry to validate, so to check that a field called<br />

username is not blank, you might use<br />

<br />

<br />

To check for an e-mail address, you might use<br />

<br />

<br />

You would then write a loop to look through forms being submitted for hidden fields and to look<br />

for ones in the form of fieldname_check. When you find one, you could use string routines to<br />

parse out the field name and the check to run on it. If the check fails, you can easily find the<br />

associated error message to show by accessing the field fieldname_errormsg.<br />

Note One of the main reasons the hidden field approach is more elegant is that we can easily<br />

have the server-side of the Web equation look at the hidden values passed and run<br />

similar validation checks. This double-checking may seem a waste of time, but it actually<br />

improves security as it is not possible to truly know if client-side validation in <strong>JavaScript</strong><br />

was run.<br />

Regardless of the method you choose, it should be clear that the approach is useful as it allows<br />

you to separate out reused <strong>JavaScript</strong> validation functions into .js files and reference from just<br />

about any form pages. However, before setting out on the task to roll your own validation<br />

routines, consider the number of people who already have needed to do the same thing. Code<br />

is out on the Web already, so it makes sense to start with a library when making your validation<br />

code. For example, take a look at<br />

http://developer.netscape.com/docs/examples/javascript.html for some sample scripts.<br />

Netscape has provided a form validation collection of code ever since <strong>JavaScript</strong> 1.0 and also<br />

provides regular expression-oriented checks as well.<br />

onchange Handlers<br />

<strong>The</strong>re is no reason you need to wait for the form to be submitted in order to validate its fields.<br />

You can validate a field immediately after the user has modified it by using an onchange event<br />

handler. For example:<br />

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

Saved successfully!

Ooh no, something went wrong!