Drupalwoo ☉

Checking Required Fields with Drupal Entity Validation

Drupal’s Entity Validation API provides a server-side way to test whether an entity satisfies the rules attached to its fields and entity type. It is particularly useful when a required field must be checked in a custom form, migration, import routine or automated workflow rather than through the standard node edit screen.

Browser validation and entity validation solve related but different problems. The HTML required attribute and Drupal Form API’s #required option improve the editing experience, yet they cannot guarantee integrity when content arrives through JSON:API, a cron-driven update, a console command or code that calls save() directly. Validating the entity before persistence closes that gap.

The examples below use Drupal 10 and 11, where content entities expose validate() and return a constraint violation list. Older Drupal releases used different helpers, so teams maintaining a legacy estate should separate those APIs instead of copying modern code into an old branch without checking its version.

What entity validation actually checks

Required status is part of a field’s definition, while the validation system turns definitions and other declared rules into violations. For a content entity, validate() examines eligible field constraints and entity-type constraints. A missing value can therefore produce a violation even when no JavaScript is running and the request did not come from a browser form.

The result is a ConstraintViolationListInterface containing each failed rule, its message and a property path. This is more useful than checking one field with isEmpty(), because it brings field requirements and custom business rules together. Core entities such as nodes, media and taxonomy terms expose related patterns, although configuration entities can define different constraints. For broader site-building context, the Drupal implementation guidance notes are a useful companion.

One important version distinction is that Drupal 7’s Entity API module supplied entity_validate() and entity_validate_field() helpers. Those functions are not interchangeable with the object-oriented validation methods used in current Drupal. A migration should map the old checks to entity constraints or explicit service logic rather than leaving two sources of truth.

Preparing an entity for a reliable check

Build or load the entity before checking it. The object must contain the correct bundle, base-field values and field values that the constraint expects; otherwise, a validation failure may describe an incomplete test object rather than bad editorial data.

$node = Node::create([
  'type' => 'service_update',
  'title' => 'Office closure notice',
  'uid' => 1,
]);

The example assumes that service_update is a node type and field_contact_phone has been configured as required. Using a real bundle name matters because node validation can vary by bundle. If the entity already exists, load it, assign the edited values, and then validate the same instance you intend to save.

Inspect empty values with the field’s isEmpty() method, but let the entity validator decide whether the field requirement is satisfied. Multi-value fields also need attention to cardinality: one populated delta can satisfy a requirement that several empty deltas do not. Check base fields such as language, owner and status where relevant, and do not assume a widget’s required marker reflects the underlying field definition.

Detecting missing required values

Calling validate() returns all detected violations instead of failing on the first one. A compact check looks like this:

$violations = $node->validate();

if ($violations->count() > 0) {
  foreach ($violations as $violation) {
    $messages[] = $violation->getMessage();
  }
}

Each violation provides a message and property path. The path commonly resembles field_contact_phone, but it may point to a deeper item path for a multi-value field. Cast a TranslatableMarkup message to a string when storing it in a log array or preparing a non-HTML response.

Do not use isEmpty() as a substitute for validation. It tells you that one field has no meaningful value; it does not prove that the field is marked required, that another field satisfies a conditional rule or that a custom constraint passed. It is useful for diagnosis and custom logic, while validate() is the authoritative result for declared constraints.

Supporting conditional and cross-field rules

An unconditional required field needs only the field setting. Conditional rules need more care. If a contact phone becomes mandatory whenever the selected service channel is phone, the form should expose that condition clearly with #required and server-side form logic. A reusable entity constraint should enforce the same rule for imports and API requests.

Drupal validates custom constraints through a constraint plugin and a constraint validator. The validator receives the entity and can inspect one or more fields, then attach a violation to the appropriate path. This small validator allows a contact phone or email address, but rejects an entity containing neither:

/**
 * @Constraint(
 *   id = "ContactChannel",
 *   label = @Translation("Contact channel", context = @Translation("Validation"))
 * )
 */
class ContactChannelConstraint extends Constraint {
  public $message = 'Supply a contact phone number or a contact email address.';
}
class ContactChannelConstraintValidator extends ConstraintValidator {
  public function validate($entity, Constraint $constraint) {
    if (!($entity instanceof NodeInterface)
        || $entity->bundle() !== 'service_update') {
      return;
    }

    if ($entity->get('field_contact_phone')->isEmpty()
        && $entity->get('field_contact_email')->isEmpty()) {
      $this->context->buildViolation($constraint->message)
        ->atPath('field_contact_phone')
        ->addViolation();
    }
  }
}

Register the validator as a validation.constraint_validator service, and attach the constraint to the entity instance when testing it:

$node->addConstraint('ContactChannel');
$violations = $node->validate();

For a persistent bundle-specific rule, add the constraint to the node entity type in hook_entity_type_alter and let the validator check the bundle. This keeps the rule active for every save path. When comparing implementation approaches, Sofcase validation guidance is useful alongside a small proof of concept that exercises the actual import or endpoint.

Applying violations in forms and services

Drupal’s standard entity forms normally convert relevant validation violations into form errors. A custom form built around EntityFormInterface or a multi-step workflow may need to call validate() itself after form values have been copied to the entity. Mapping matters: setErrorByName() expects a form element name, which may not equal a violation’s full property path.

$violations = $entity->validate();

if ($violations->count() > 0) {
  foreach ($violations as $violation) {
    $form_state->setErrorByName(
      'field_contact_phone',
      (string) $violation->getMessage()
    );
  }
}

Call this validation after building the entity and before save(). Avoid adding the same checks to a standard node form because that can display duplicate messages. If several violations belong to one field, combine or prioritise the messages deliberately rather than assuming every property path can be passed directly to setErrorByName().

Do not assume that direct save() calls universally invoke every entity constraint. A service, migration or cron callback should validate first, handle every violation, and only persist a clean entity. JSON:API performs entity validation for its write routes, but a custom controller still needs an explicit validation policy. The same rule should produce the same outcome regardless of the entry point.

Testing validation behaviour

Start with a kernel test that creates the required bundle, builds an entity with the missing value and asserts that validate() returns a violation. Add a second case with valid values and assert an empty list. Kernel tests are fast enough for repeated field combinations and catch differences between the interface configuration and the entity API.

Then add a functional test that submits the form without the field, checks the error message, fills the field and confirms a successful save. Assert the stored value as well as the screen message. A browser test can confirm focus and error presentation, but the server-side test remains essential because HTML5 required attributes can be bypassed.

Time zones deserve attention because a deployment in Melbourne during AEDT can keep a cron import running while a Perth team is still on AWST; store data consistently and test its local display. A quick arvo smoke test should cover the browser form, an API response and a direct service save rather than relying on one happy path.

Recommended practices for reliable Drupal validation

Australian Drupal projects commonly involve small specialist agencies, internal maintainers and larger providers working across different maintenance arrangements. A reusable validation layer reduces duplicated business rules and makes handovers clearer, especially when an agency later transfers a site to an in-house team.

Completeness is not the same as compliance. Contact, identity or marketing fields may also need consent, retention and disclosure handling under Australian privacy and anti-spam rules. Entity validation can confirm that a value exists; it cannot decide whether collecting or publishing that value is lawful.