How to Validate Web Forms - dummies

By Steve Suehring, Janet Valade

Form validation is the process by which you examine the data from a web form to make sure it’s the correct and expected data in the right format. There are two general types of validation, client-side and server-side.

  • Client-side validation typically occurs with JavaScript right within the visitor’s web browser.

  • Server-side validation occurs in the code running on the server, in this case, the PHP code.

Always assume bad data

Rule #1 in programming is to always assume that the data you’re receiving is incorrect and only after it’s been proven correct should it be used. Working with this assumption greatly simplifies your task as a programmer.

With this assumption, you no longer need to try to think of every way that a user could break your program. Rather, you merely need to think about the correct way to use it, and then make sure that your version of correctness is being followed.

Never assume JavaScript

A mistake made by new and experienced programmers alike is to assume that JavaScript will be enabled in the visitor’s browser. With that assumption, the programmers perform their validation in JavaScript and only do minimal validation in PHP, where it really counts.

Unfortunately, JavaScript may not always be available, and even when it is, malicious users can still send bad data to the server by skipping the JavaScript checks. No amount of triple-extra checking to make sure JavaScript is enabled will help with that.

The only solution is to never assume that JavaScript validation has occurred at all and always perform rigorous validation in PHP. Once the data gets into PHP, the user no longer controls it and the number of things that can go wrong decreases.

Sometimes mirror client- and server-side validation

When you implement a check in JavaScript, for example, to make sure that a ZIP code is five digits, that same type of check should also be added to the PHP code. Obviously, keeping these in sync can become a bit cumbersome, and there are certain times when a validation check might not be appropriate on the client side.

For example, a website visitor’s selection from a drop-down for state (a menu that includes Arizona, California, Wisconsin, and so on) probably doesn’t need to be checked in the JavaScript, but it definitely does need to be checked in the PHP code.

As a general rule, though not always, you sometimes will mirror the validation logic between JavaScript and PHP.