Skip to content

Instantly share code, notes, and snippets.

@tamouse
Created September 26, 2012 20:35
Show Gist options
  • Select an option

  • Save tamouse/3790433 to your computer and use it in GitHub Desktop.

Select an option

Save tamouse/3790433 to your computer and use it in GitHub Desktop.
Handling form validation with error messages near problem fields.
<?php
/**
* an example of validating a form and showing errors
* by the incorrect fields. This is just a fragment showing how one
* implement a scheme to provide error information close to the form
* field where the error has occured. This provides better usability
* for the user to see exactly where the error occured and what to do
* to fix it. What is presented here is conceptual only; actual
* hardened application code would be more complete.
*
* Author: Tamra Temple <tamara@tamaratemple.com>
* License: Public Domain.
*/
/**
* For the purposes of testing, turn on error reporting
*/
error_reporting(-1);
ini_set('display_errors',true);
ini_set('display_startup_errors',true);
/**
* Initialize arrays
*/
$contactinfo=array();
$contactinfo['name'] = '';
$contactinfo['phone'] = '';
$contactinfo['email'] = '';
$errormsg=array();
/**
* For debugging, show what is coming in on the $_POST variable
*/
echo DebugValues('$_POST',$_POST);
/**
* Process the form submission
*/
if (isset($_POST['submit'])) {
/**
* assign and validate $_POST variables
*/
$contactinfo['name'] = @$_POST['name'];
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errormsg['name'] = "Name cannot be empty";
} elseif (false == preg_match('/^[[:alnum:][:space:]\-.,]+$/',$_POST['name'])) {
$errormsg['name'] = "Name can only contain letter, digits, spaces, commas, periods and hyphens.";
}
$contactinfo['email'] = @$_POST['email'];
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errormsg['email'] = "Email cannot be empty";
} elseif (false == preg_match('/^[[:alnum:]_\-.+]+@[[:alnum:]_\-.]+$/',$_POST['email'])) {
$errormsg['email'] = "Email addresses must be of the form mailbox@address.
mailbox can consist of letters, digits, underscore, hyphen, period, and plus.
address can consist of letters, digits, underscore, hyphen, and period.";
}
$contactinfo['phone'] = @$_POST['phone'];
if (!isset($_POST['phone']) || empty($_POST['phone'])) {
// do nothing -- it's ok if phone is empty
} elseif ( false == preg_match('/^[[:digit:][:space:]\-.+()]+$/',$_POST['phone'])) {
$errormsg['phone'] = "Invalid phone number.
Phone numbers can only contain digits, spaces, hyphens, periods, plus signs, and parentheses.";
}
}
/**
* Dump out arrays for debugging
*/
echo DebugValues('$contactinfo',$contactinfo);
echo DebugValues('$errormsg',$errormsg);
/**
* Let's do a little styling
*/
echo <<<HTML
<style type="text/css" media="screen">
form {border:1pt solid black; margin: 20px; padding: 5px;}
label { font-weight: bold; min-width: 150px; display:inline-block; }
label.required:after {content:" [Required]"; color: #33F; font-size: 80%; font-style:italic;}
input { font-family: monospace; display:inline-block; min-width: 200px; }
input.required {background-color: #DDF; }
.errormsg { font-style: italic; font-size: 80%; color: red; display: inline-block; max-width: 40%; margin-bottom: 5px; vertical-align: top; }
.errormsg:before {content:"**FIELD ERROR**: ";font-weight:bold;}
.errors { font-weight: bold; border: 1pt solid red; color: #F00; background: #FDD; margin: 10px 20px; padding: 5px; }
.debug { color: #666; font-size: 90%; }
</style>
HTML;
/**
* Display form (note that we're displaying only a fragment of an HTML
* page. Modern browsers don't have and difficulty with this, but you
* wouldn't want to do this in practice.)
*/
if (!empty($errormsg)) echo "<p class='errors'>There were errors in your data, please fix and resubmit.</p>";
echo "<form method='POST' id='contactinfo' action=''>\n";
echo "<label class='required' for='name'>Name:</label>
<input class='required' name='name' type='text' value='${contactinfo['name']}' />\n";
if (isset($errormsg['name']))
echo "<span class='errormsg'>".nl2br($errormsg['name'])."</span>\n";
echo "<br /><label class='required' for='email'>Email:</label>
<input class='required' name='email' type='text' value='${contactinfo['email']}' />\n";
if (isset($errormsg['email']))
echo "<span class='errormsg'>".nl2br($errormsg['email'])."</span>\n";
echo "<br /><label for='phone'>Phone:</label>
<input name='phone' type='text' value='${contactinfo['phone']}' />\n";
if (isset($errormsg['phone']))
echo "<span class='errormsg'>".nl2br($errormsg['phone'])."</span>\n";
echo "<br /><input type='submit' name='submit' value='Send Info' />
</form>
";
function DebugValues($msg='',$var=null)
{
return sprintf("<div class='debug'>%s:<pre>%s</pre></div>",$msg,htmlentities(print_r($var,true)));
}
@tamouse

tamouse commented Sep 26, 2012

Copy link
Copy Markdown
Author

@tamouse

tamouse commented Sep 26, 2012

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment