In D7 there appear to be various methods by which a module can carry out validation of a form's fields, including:

  • #element_validate callback
  • #validate callback
  • hook_field_validate() implementation
  • hook_form_validate() implementation
  • hook_field_attach_validate() implementation

Firstly, can anyone list the execution order of the above?

Secondly, can anyone please explain why one might choose to use a callback instead of a hook or a hook instead of a callback?

  • #element_validate is used to provide validation for a specific element.
  • #validate is used for the form, and for elements that cause the form to submit (button, image_button, submit). It provides the names of extra functions to call during the validation process.
  • hook_field_validate() is for validating fields (not standard form elements). This doesn't necessarily take place in the context of a form submission.
  • There's isn't a hook_form_validate() - by convention if a function called FORM_ID_validate() exists then it will be used as part of the above #validate array for the form. This is used to validate any part of the form, not just a specific element.
  • hook_field_attach_validate() runs as validation when fields are attached to an entity, it doesn't run in the context of a form (see field_attach_validate())

Not all of the above are executed at any one time, or in any single context, so listing an execution order isn't possible.

Hopefully the above distinctions will make it obvious which one to use in what circumstance.

  • Very helpful, thank you. Would you mind elaborating on the difference between "element" and "field" in the context of #element_validate vs hook_field_validate()?
    – morbiD
    Jul 4 '13 at 15:05
  • In Drupal terms a field is something that attaches to an entity (not to be confused with a form field, e.g. an <input>). It will likely have an associated widget, which defines the actual form element that gets used in a form to supply data for the field. Fields are defined using hook_field_info(). Elements refer to the basic widgets that can be added to any type of Drupal form, i.e. they're not dependant on a Drupal field in any way. These are defined by hook_element_info(). It does get confusing - some fields use standard-defined elements to create their widgets
    – Clive
    Jul 4 '13 at 15:15
  • The important thing to note is that in Drupal, when we talk about a field, we're not referring to a form field like a textfield, textarea, select list, etc. We're talking about a field attached to an entity
    – Clive
    Jul 4 '13 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.