|MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA|
Form Validationby Paul Adams and Apple Developer Connection
Any sort of interactive site is going to have form inputs -- a place where your users input who they are, what they want to buy, where they live, and so forth. This data is passed to whatever handles your back end -- a Perl CGI script, a PHP engine, a database like Oracle, or some other technology you've invested in. Whatever system is back there, you can bet that it doesn't appreciate having its time wasted with bogus information, and chances are the user doesn't appreciate it either. If the data the user submits to the CGI contains an error, there will be a noticeable lag -- typically several seconds -- before the information travels over the Internet to the server, is examined on the server, and then returns to the user along with an irritating error message.
The Script's Purpose
A master function, called
This function calls a series of subfunctions, each of which checks a single form element for compliance with a specific string format and returns a message describing the error. If the function returns an empty string, we know the element complies.
Here's the routine that checks to see if the user entered anything at all in the
We pass the value of the username field to this function, which compares that value to an empty string (
Next, we want to forbid certain characters from appearing in usernames. Specifically, we want to allow only letters, numbers, and underscores. We can test for that using regular expressions and the
By now, we've run the username through three tests. If it's passed all three, it's OK by us. We give the username a passing grade and move along to the next field.
For the password field, we want to constrain the length again (this time, we'll keep it between 6 and 8 characters), and we want to allow only letters and numbers -- no underscores this time. So we have to use a new regular expression to define which characters we're banning. This one, like the last one, includes
When it comes to passwords, we want to be strict with our users. It's for their own good; we don't want them choosing a password that's easy for intruders to guess, like a dictionary word or their kid's birthday. So we want to insist that every password contain a mix of uppercase and lowercase letters and at least one numeral. We specify that with three regular expressions,