Data validations
Validating data
It is important to establish requirements for acceptable incoming data and then to enforce those requirements in the application’s code. Imposing data requirements is called validating data. If data passes validations, then it meets all requirements and the application can use it. If data fails validations, then it was not acceptable and the application should reject it.
Most applications will require some amount of custom validations to fit their specific needs. However, there are a few standard validations which get used frequently which are worth adding to one’s development toolbox.
- Presence
- Length
- Type
- Inclusion in a set
- Uniqueness
- Format
It can be helpful to write functions for these validations and then keep them as a library for repeated use.
Here are two example functions which validate data presence and string length.
<?php
// is_blank('abcd')
function is_blank($value) {
return !isset($value) || trim($value) === '';
}
// has_length('abcd', ['min' => 3, 'max' => 5])
function has_length($value, $options=[]) {
if(function_exists('mb_strlen')) {
$length = mb_strlen($value, 'UTF-8');
} else {
// Fallback counts bytes, not characters; see the note below.
$length = strlen($value);
}
if(isset($options['max']) && ($length > $options['max'])) {
return false;
} elseif(isset($options['min']) && ($length < $options['min'])) {
return false;
} elseif(isset($options['exact']) && ($length != $options['exact'])) {
return false;
} else {
return true;
}
}
?>
Note that has_length() prefers mb_strlen($value, 'UTF-8') over strlen() when the mbstring extension is available. PHP’s strlen() returns the number of bytes, not the number of characters, so multi-byte UTF-8 input would be over-counted against the min/max/exact limits—a single emoji such as 😀 encodes to 4 bytes and would fail an ['exact' => 1] check. mb_strlen() counts each multi-byte character as 1. It is provided by PHP’s mbstring extension, which is not enabled by default in all PHP builds, so the function checks function_exists('mb_strlen') first and falls back to strlen() where mbstring is unavailable. The fallback keeps the helper working everywhere, but it counts bytes—enable mbstring when accurate character counts for non-ASCII input matter.
Other built-in PHP functions which are useful for crafting validations include:
- Presence: isset, empty, is_null
- Length: mb_strlen, strlen, trim
- Type: is_string, is_int, is_float, is_array, is_bool
- Inclusion: in_array, strpos, strstr
- Format: preg_match
The uniqueness validation is unique. It usually requires making a database query to determine if a value (such as a username) already exists.
Once validation functions are written, they can be used to validate the form data. Keep track of validation errors so that the user can be informed about the specific issues.
Remember that incoming request data cannot be trusted to include every expected field—a hand-crafted POST request can omit first_name entirely, and reading a missing array key raises an “Undefined array key” warning as of PHP 8.0. Use the ?? operator (introduced on the Form processing page) to supply a default value before validating.
<?php
$errors = [];
$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
if (is_blank($first_name)) {
$errors[] = "First name cannot be blank.";
} elseif (!has_length($first_name, ['min' => 2, 'max' => 20])) {
$errors[] = "First name must be between 2 and 20 characters.";
}
if (is_blank($last_name)) {
$errors[] = "Last name cannot be blank.";
} elseif (!has_length($last_name, ['min' => 2, 'max' => 30])) {
$errors[] = "Last name must be between 2 and 30 characters.";
}
?>
Note that the ! is the logical operator for “not”. This code only adds an error message if “not has_length”.