You are here

function dimension_field_validate in Dimension 7

Implements hook_field_validate().

File

./dimension.module, line 186

Code

function dimension_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  if (empty($field)) {

    // This got called by the field settings form, we ignore it for now.
    return;
  }
  $settings = $instance['settings'];
  list($has_length, $has_more) = _dimension_get_modes($field['settings']['mode']);
  $field_names = $has_length ? array(
    'length',
  ) : array();
  $field_names += $has_more ? array(
    'height',
    'width',
  ) : array();
  foreach ($items as $delta => $item) {
    foreach ($field_names as $field_name) {
      $value = trim($item[$field_name]);
      $field_settings = $settings['fields'][$field_name];
      switch ($field_settings['datatype']) {
        case DIMENSION_DATATYPE_INTEGER:
          if (strval((int) $value) !== $value) {
            $errors[$instance['field_name']][$langcode][$delta][] = array(
              'error' => 'Dimension requires an integer value',
              'message' => t('The value for %label needs to be an integer.', array(
                '%label' => $field_settings['label'],
              )),
            );
          }
          break;
        case DIMENSION_DATATYPE_DECIMAL:
          if (strval((double) $value) !== $value) {
            $errors[$instance['field_name']][$langcode][$delta][] = array(
              'error' => 'Dimension requires a decimal value',
              'message' => t('The value for %label needs to be an decimal.', array(
                '%label' => $field_settings['label'],
              )),
            );
          }

          // TODO: Finalize validation to make sure that the maximum number of decimals is not exceeded.
          break;
        default:
          break;
      }
      if ($value <= 0) {

        // Dimensions always have to be positive.
        $errors[$instance['field_name']][$langcode][$delta][] = array(
          'error' => 'Dimension with negative value',
          'message' => t('The value for %label needs to be positive.', array(
            '%label' => $field_settings['label'],
          )),
        );
      }
    }
  }
}