SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Forms (III)

PHP Example #66

Validating data in forms

The previous example did not show any message if the input was not valid. In this example, we will add such functionality, which is essential in any well-rounded form. Ideally, when someone sends data that is invalid, it should be displayed an error message that explains the error and which format is allowed for input. Some validation techniques use regular expressions, which are powerful patterns used for the coincidence of text, written in a particular language. A proper configuration of validation should be enough to prevent SQL injection attacks on the input of the form.

In this enlarged version of the previous example, the form asks for different formats of input data, that are validated by the corresponding decision statements that are placed inside the validation function. With the function strlen() we can check the lenght of a string and by deleting the spaces with the function trim() we can verify if text has been actually typed. With the functions intval() and floatval() we can verify if the input string contains integer or float numbers, while the function strval() will convert these numbers into a string that can be compared with $_POST[].

The function strtotime() accepts certain string parameters and returns a date value in format yyyy-mm-dd, while the function time() returns the current time, which in this example is used to calculate if the submitted date is not older than six months. And finally, a complex regular expresion is used to verify that the submitted e-mail address has the common format (name@provider.domain).

<?php
// Logic to do what is correct based in the hidden parameter _submit_check
if (! array_key_exists('_submit_check', $_POST)) {
$_POST['_submit_check'] = 0;
}
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
// Do something when the form is sent
function process_form() {
print "Welcome, " . $_POST['my_name'];
}
// Show the form
function show_form($errors = '') {
// If some errors were passed, print them
if ($errors) {
print 'Please correct these errors: <ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
print 'Your name (a string):<br/>';
print '<input type="text" name="my_name"/><br/>';
print 'Your age (an integer number):<br/>';
print '<input type="text" name="my_age"/><br/>';
print 'Your e-mail (a string):<br/>';
print '<input type="text" name="my_email"/><br/>';
print 'Your price (an integer or float number):<br/>';
print '<input type="text" name="my_price"/><br/>';
print 'Date (Year, 4 digits):<br/>';
print '<input type="text" name="year"/><br/>';
print 'Date (Month, 2 digits):<br/>';
print '<input type="text" name="month"/><br/>';
print 'Date(Day, 2 digits):<br/>';
print '<input type="text" name="day"/>'<br/>;
print '<input type="submit" value="Submit!"/>';
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
}
// Verify the input of the form
function validate_form() {
// Start with an empty array of error messages
$errors = array();
// Add an error message if the name is too short
if (strlen($_POST['my_name']) < 3) {
$errors[] = 'Your name must have at least 3 letters long.';
}
// Add an error message if nothing has been typed
if (strlen(trim($_POST['my_name'])) == 0) {
$errors[] = 'You must enter your name.';
}
// Add an error message if the age is not a number or it is out of a certain range
if ($_POST['my_age'] != strval(intval($_POST['my_age']))) {
$errors[] = 'Please enter an integer number for your age.';
} elseif (($_POST['my_age'] < 18) || ($_POST['my_age'] > 65)) {
$errors[] = 'Your age must be at least 18 and no more than 65.';
}
// Add an error message if an e-mail address has not been typed
if (strlen($_POST['my_email']) == 0) {
$errors[] = 'You must enter an e-mail address.';
}
// Add an error message if the e-mail address has
// been typed with incorrect syntax
if (! preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i',
$_POST['my_email'])) {
$errors[] = 'Please enter a valid e-mail address.';
}
// Add an error message if the price is not an integer or a float number
if ($_POST['my_price'] != strval(floatval($_POST['my_price']))) {
$errors[] = 'Please enter a number for the price.';
}
// Obtain the timestamp for 6 months ago
$range_start = strtotime('6 months ago');
// Obtain the timestamp for current time
$range_end = time();
// A four-digit year is in $_POST['year']
// A two-digit month is in $_POST['month']
// A two-digit day is in $_POST['day']
$submitted_date = strtotime($_POST['year'] . '-' .
$_POST['month'] . '-' . $_POST['day']);
if (($range_start > $submitted_date) || ($range_end < $submitted_date)) {
$errors[] = 'Please choose a date less than six months old.';
}
// Return the array (possibly empty) of error messages
return $errors;
}
?>
Your name (a string):

Your age (an integer number):

Your e-mail (a string):

Your price (an integer or float number):

Date (Year, 4 digits):

Date (Month, 2 digits):

Date(Day, 2 digits):