Skip to content

Instantly share code, notes, and snippets.

@m-renaud
Last active December 14, 2015 00:29
Show Gist options
  • Save m-renaud/4999283 to your computer and use it in GitHub Desktop.
Save m-renaud/4999283 to your computer and use it in GitHub Desktop.
Validate a form using php.
<?php
session_start();
header("Content-Type: text/html");
$errors = array();
// Reset form.
if(array_key_exists('clearForm', $_POST))
{
unset($_SESSION);
$_SESSION = array();
header("Location: form.php");
}
// Field refers to form fields of the form.php page.
$field = array(
'month' => 'expiryMonth',
'year' => 'expiryYear',
'cc_type' => 'cardType',
'cc_num' => 'cardNumber',
'email' => 'emailAddress'
);
// Set validators and messages.
$validators = array(
$field['month'] => function($key){ return $_POST[$key] != "--"; },
$field['year'] => function($key){ return $_POST[$key] != "----"; },
$field['cc_type'] => function($key){ return $_POST[$key] != "notSelected"; },
$field['cc_num'] => function($key){ return true; /* need to put regex here */ },
$field['email'] => function($key){ return true; /* need to put regex here */ },
);
$messages = array(
$field['month'] => "Please select an expiry month",
$field['year'] => "Please select an expiry year",
$field['cc_type'] => "Please select a credit card type",
$field['cc_num'] => "Please enter a valid card number",
$field['email'] => "Please entar a valid email address"
);
// Validate the form given the validators, messages and an errors array to populate.
validate_form($validators, $messages, $errors);
foreach($errors as $key => $err)
{
echo "$key: $err<br/>";
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
function validate_form(&$validators, &$messages, &$errs)
{
foreach($validators as $key => $func)
{
validate_field($key, $func, $errs, $messages[$key]);
}
}
function validate_field($key, &$validation_function, &$err_array, $err_msg)
{
if(!(array_key_exists($key, $_POST) && $validation_function($key) ))
$err_array[$key] = $err_msg;
}
?>
@scottnguyen
Copy link

I think this woud be nicer... default compiler won't catch errors but there are probably tools that can sniff out possible errors anyway if you do it this way:

$month = "expiryMonth";
$year = "expiryYear";
$cc_type = "cardType";
$cc_num = "cardNumber";
$email = "emailAddress";
$fields = array( $month, $year, $cc_type, $cc_num, $email);

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