SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Forms (V)

PHP Example #68

Validating data in forms

If we want a select menu that has different option values, we have to use an associative array, where each key is the value attribute for the corresponding option and each value is the corresponding selection shown in the list. From the previous example, the differences in the source code are only in the declaration of the array, the foreach() loop and the validation structure for the select menu. Now, instead of checking the values in the array (which are the ones displayed in the list), we check their associated keys in the validation process.

$sweets = array('puff' => 'Sesame Seed Puff',
'square' => 'Coconut Milk Gelatin Square',
'cake' => 'Brown Sugar Cake',
'ricemeat' => 'Sweet Rice and Meat');
// 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()) {
} else {
} else {
// 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 'Your order:<br/><select name="order">';
// $val is the option value and $choice is what is shown
foreach ($GLOBALS['sweets'] as $val => $choice) {
print "<option value=\"$val\">$choice</option>\n";
print '</select><br/>';
print '<input type="submit" value="Order"/>';
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.';
// Add an error message if the option sent is not one of the ones
// contained in the array $sweets[]
if (! array_key_exists($_POST['order'], $GLOBALS['sweets'])) {
$errors[] = 'Please choose a valid order.';
// 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):

Your order: