Skip to content

Instantly share code, notes, and snippets.

@247rahimab
Forked from thepsion5/example.php
Created January 19, 2017 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 247rahimab/1544f7c371845a34c0619a369ff40126 to your computer and use it in GitHub Desktop.
Save 247rahimab/1544f7c371845a34c0619a369ff40126 to your computer and use it in GitHub Desktop.
An extremely simple example of how to create a generic validation function using PHP's filter_input() function and/or callbacks
<?php
//Define how each POST field is validated
$fieldValidation = [
'username' => 'required',
'first_name' => 'required',
'last_name' => 'required',
'website' => 'website',
'email' => 'email',
'pass' => 'password',
];
//validate each field, redirect and display appropriate error messages as needed
$validFields = [];
foreach($fieldValidation as $field => $validationType) {
$validFields[$field] = validate_post_field($validationType, $field);
}
<?php
/**
* Validates a POST field when provided a valid type and a field name
* @see http://php.net/manual/en/function.filter-input.php
* @see http://php.net/manual/en/filter.filters.validate.php
*
* @param string $type A valid type use for validation
* @param string $fieldName The name of the POST field
* @param array $filterTypeOptions Optional parameters supplied to the filter method
* @return bool True if the field is valid, false otherwise
*/
function validate_post_field($type, $fieldName, array $filterTypeOptions = [])
{
$filterType = '';
$alternativeValidationFunction = null;
//determine how the data will be filtered
switch($type) {
case 'email':
$filterType = FILTER_VALIDATE_EMAIL;
break;
case 'bool':
$filterType = FILTER_VALIDATE_BOOLEAN;
break;
case 'website':
$filterType = FILTER_VALIDATE_URL;
break;
case 'string':
$filterType = FILTER_VALIDATE_STRING;
break;
case 'required':
//If the type is too complex to use one of the native validation types, a function can be used instead
$alternativeValidationFunction = 'validate_not_empty';
break;
case 'password':
$alternativeValidationFunction = 'validate_strong_password';
break;
default:
throw new InvalidArgumentException("The specified data type [$type] is not supported");
break;
}
if($filterType) {
return filter_input(INPUT_POST, $fieldName, $filterType, $filterTypeOptions);
}
$value = isset($_POST[$fieldName]) ? $_POST[$fieldName] : null;
return $alternativeValidationFunction($value, $filterTypeOptions);
}
function validate_not_empty($value, array $options = [])
{
//being lazy here, note that a value of "0" will cause this to fail
return $value != null;
}
function validate_strong_password($value, array $options = [])
{
//I'll leave this as an exercise for the user
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment