7.x field.api.php hook_field_attach_validate($entity_type, $entity, &$errors)

Act on field_attach_validate().

This hook is invoked after the field module has performed the operation.

See field_attach_validate() for details and arguments.


$entity_type: The type of $entity; e.g., 'node' or 'user'.

$entity: The entity with fields to validate.

array $errors: The array of errors (keyed by field name, language code, and delta) that have already been reported for the entity. The function should add its errors to this array. Each error is an associative array with the following keys and values:

  • error: An error code (should be a string prefixed with the module name).
  • message: The human readable message to be displayed.

Related topics


modules/field/field.api.php, line 1338
Hooks provided by the Field module.


function hook_field_attach_validate($entity_type, $entity, &$errors) {

  // Make sure any images in article nodes have an alt text.
  if ($entity_type == 'node' && $entity->type == 'article' && !empty($entity->field_image)) {
    foreach ($entity->field_image as $langcode => $items) {
      foreach ($items as $delta => $item) {
        if (!empty($item['fid']) && empty($item['alt'])) {
          $errors['field_image'][$langcode][$delta][] = array(
            'error' => 'field_example_invalid',
            'message' => t('All images in articles need to have an alternative text set.'),


izus’s picture

FieldValidationException If validation errors are found, a FieldValidationException is thrown. The 'errors' property contains the array of errors, keyed by field name, language and delta.

Use it as in the example :

        $errors[$field_name]][$langcode][$delta][] = array(
          'error' => 'field_example_invalid',
          'message' => t('Color must be in the HTML format #abcdef.'),
Propaganistas’s picture

Beware of the typo in the first line (superfluous square bracket).

The correct code is:

  $errors[$field_name][$langcode][$delta][] = array(
    'error' => 'field_example_invalid',
    'message' => t('Color must be in the HTML format #abcdef.'),
dsnopek’s picture

I was using this hook to validate the content of 'link_field' fields from the Link module: https://www.drupal.org/project/link

But the error wouldn't actually be shown on the form, until I also set 'error_element' on the error. The code that works looks like this:

$errors[$field_name][$langcode][$delta][] = array(
  'error' => 'mymodule_error_code',
  'message' => t('Here's the message.'),
  'error_element' => array(
    'url' => TRUE,

Where 'url' was the value within $item that had the validation error.

Hopefully this'll help someone else!