Drupal - Validate all instances of a field programmatically

You could implement hook_field_validate and check if its the correct instance. Doesnt work if the field is not defined by the module.

One way to build that would use hook_form_alter and add element_validator if the field exists on the form.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if (isset($form['field_phone'])) {
      $form['field_phone']['#element_validate'][] = 'mymodule_somevalidator';
    }
 }

function mymodule_somevalidator($element, &$form_state) {
  if (!empty($element['#value']) && !is_numeric(parse_size($element['#value'])) {
    form_error($element, t('The "!name" must be x', array('!name' => t($element['title']))));
  }
} 

Try the Field Validation module.

You still have to add proper validation to each field you want to validate.


From field_attach_form_validate:

There are two levels of validation for fields in forms: widget validation, and field validation.

for widget validation you may follow the hook_form_alter path. This is hard to generalize since you need to know details about how the form is built. For example elements or values may be nested for some entities.

IMO, it's best to do field validation. It is performed by implementing hook_field_attach_validate. Here's a simple example:

function hook_field_attach_validate($entity_type, $entity, &$errors) {
  if (isset($entity->field_phone)) {
    $errors['field_phone'][LANGUAGE_NONE][0][] = array(
      'error' => 'error_key',
      'message' => t('Error message'),
    );
  }
}

error_key is used by hook_field_widget_error to flag a form element when a widget is compound of several elements. For example, in text field's implementation of this hook the error key text_summary_max_length is used to flag an element within the widget structure.

In the general term, the error key is not used for widgets with a single element. In the case of phone field type (that I assume you're using), they provide a compound widget but don't implement error distribution to elements, so just ignore it.

Tags:

Entities

7