Home | All Questions | alt.html FAQ >

Are there any problems with using Javascript to validate a form?

The problem/opportunity with Javascript is that it runs in a browser (the client) which is great when its enabled, but a different story when Javascript is disabled. Validating a form using javascript before submitting to the server does reduce the potential load on the webserver - so its a good thing, for both the user and the webmaster.

There is a tendancy, however, to completely rely on javascript validation - and with a lack of server-side validation to check the validity, there is a big security hole.

During the early days of e-commerce certain companies adopted a Javascript based shopping card, using Javascript objects and cookies all contained in the browser. When the customer clicked the checkout button, the Javascript details were then sent to the server which then shipped the order and billed the client accordingly. During these days certain people obtained brand new laptops for $1, brand new hi-fi's and computers very cheaply indeed. What happened was that the server didn't validate all orders to check the prices from the javascript shopping trolley were correct - or even rational. They assumed Javascript would handle all of that.

What these companies didn't take into account that Javascript, being a client-side technology, a browser component, that it (the item prices) could be modified by a bright user before being sent to the server. And since the server implicitly trusts the Javascript, no further checks are done. $1 for a laptop.

This reason defines the major rule in using Javascript: Never rely on Javascript

That's not to say never use Javascript. Use it, it has great benefits and usability advantages, but don't rely on it always giving you the "right" answer. For shopping carts, check every price and quantity against a database on the server, check the total is correct too, and the credit card number and the zip-code.

Anything client-side can be disabled by the user. Server-side checks cannot.

Certain "professional" webdevelopers/programmers suggest forcing the user to enable Javascript - ignoring the safety implications for both the user (Windows worms and trojans), and the website owner (selling items way below their actual values thus incurring massive losses). Be wary of this kind of web developer - they have no concerns about ethical practices and quality.

Don't believe that a form will always validate when the submit button is clicked. This next snippet of code, pasted in the location bar of a user's browser and then run, overwrites the onClick event on all forms on a page: javascript:for (i=0; i<document.forms.length; i++) document.forms[i].onsubmit=null; void 0;

Recommended Resources

Discussion

Related Questions