0

I built a custom field type using the Field API. In hook_field_validate I have some logic to validate some very custom stuff, but when I tried to add a "This field is required" validation, I realized this hook runs on the from that you fill when you're adding a field to an entity. Then, I implemented hook_field_is_empty, which I know runs when the entity saves. Problem is, even if the hook runs and the field is empty, no validation occurs (i.e. the user doesn't get the "this is required" message, and the form submits).

So, what's the right way to do a "this field is required" validation?

2 Answers 2

0

Probably a stupid question but have you tried using the #required setting when you created the field i.e.

'#type' =>
'textfield', 
'#title' => t('Subject'), 
'#default_value' => $node->title, 
'#size' => 60, 
'#maxlength' => 128, 
'#required' => TRUE,

from Form API reference https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#required

2
  • I'm not using the form API directly, so no, but I did configure the field instance to be "required".
    – cambraca
    Commented Mar 27, 2015 at 22:08
  • Also found function my_module_element_validate($element, &$form_state) { switch ($element['#type']) { case 'textfield': if ($element['#value'] == '') { form_error($element, t('Case Name may not be blank.')); } break; case 'checkboxes': if (empty (link is external)($element['#value'])) { form_error($element, t('You must give at least one role access to this state.')); } break; } }
    – mknezel
    Commented Mar 27, 2015 at 22:08
0

In Drupal 8, you want to look at Constraints. Constraints are put on the field, so that the value to be stored is validated regardless of the source (web/app etc).

https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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