Using PHP To Validate Form Fields


























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.









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.








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.



Enjoy Friends.........!

0 comments:

Post a Comment