JDT

 

John Dixon
Technology
Limited

 
Google

Using PHP to Validate Fields on a Form


When it comes to validating the data that people enter into fields in a form on a web page, JavaScript is quite often used to perform client-side validation. PHP can, however, be used to perform the validation on the server, before the data is processed. This provides a more elegant way of performing the validation because when there is an issue with a particular field, the user is returned to that field rather than a general popup being displayed, which is the way the validation works using JavaScript.

Look at the following form.

Simple Form

This form contains a function at the top of the web page (fieldError) that is called to check whether there is an error for the 'current' field. In this example we only have one field called 'name', but the same function call could be made for as many fields as necessary.

If there is an error for the field, an appropriate error message (see below) is displayed above the field. This is useful because where a form contains several fields, it is sometimes difficult to know to which field a JavaScript-generated error applies.

Form Validation

This script is the form handler. In this example, the only thing the form handler does is to check that the 'name' field is not empty. In a 'real' form handler, the script would go on to process the data in some way once it had been validated.

The $errors array is initially cleared to make sure that any previous errors are removed, otherwise the script would keep thinking that the errors still applied.

After that the $name variable is checked to see if it contains any data. If it is empty, an error message is inserted into the $errors array. A check is then performed to see if the $errors array contains any items; if it does, the user is returned to the form and the error message is displayed above the field.


Author: John Dixon
John Dixon Technology Ltd







Go back to PHP Tutorials home page

Go back to Tutorials home page



Earnings Tracker is John Dixon Technology's FREE open source accounting / bookkeeping software tool.

Aimed at UK contractors and freelancers, Earnings Tracker enables you to perform bookkeeping and accounting tasks, helping you to keep track of your company's earnings and outgoings.

Earnings Tracker can also be used simply as a dividend, corporation tax, or VAT calculator.

Need free accounting software
 







JDT

© 2007-2009 - John Dixon Technology Ltd

Privacy Statement

Terms & Conditions