Codepath

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=[]) {
    $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;
    }
  }
?>

Other built-in PHP functions which are useful for crafting validations include:

  • Presence: isset, empty, is_null
  • Length: 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.

<?php
  $errors = [];
  if (is_blank($_POST['first_name'])) {
    $errors[] = "First name cannot be blank.";
  } elseif (!has_length($_POST['first_name'], ['min' => 2, 'max' => 20])) {
    $errors[] = "First name must be between 2 and 20 characters.";
  }
  if (is_blank($_POST['last_name'])) {
    $errors[] = "Last name cannot be blank.";
  } elseif (!has_length($_POST['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".

Fork me on GitHub