Module Development

Validating and Saving Field Data for Drupal 7

This page is archived

We're keeping this page up as a courtesy to folks who may need to refer to old instructions. We don't plan to update this page.

Alternate resources

Sprout Video

Before our field can save user provided data we need to use hook_field_validate() and hook_field_is_empty() to perform validation on field data. In certain context values like 0, FALSE, and NULL can all be a valid value. In fact, even a blank space could be valid input for a field. As such, it's not possible for Drupal to know what constitutes an empty state for a field without a little extra help. The same is true for checking if the value of a field is valid.

Examples:


/**
 * Implementation of hook_field_is_empty().
 */
function rgb_field_is_empty($item, $field) {
  if (empty($item['rgb']) || empty($item['label'])) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_field_validate().
 */
function rgb_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach($items as $delta => $item) {
    if (!empty($item['rgb'])) {
      // Make sure it's 6 characters.
      if (drupal_strlen($item['rgb']) !== 6) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'rgb_length',
          'message' => t('%name: the hex color must be 6 characters.', array('%name' => $instance['label'])),
        );
      }
    }
  }
}

Additional resources

hook_field_validate()

hook_field_is_empty()

Legacy Module Development