You can add custom validation for Drupal entities by adding "constraints" (a concept from Symfony, the PHP framework on top of which Drupal is built) to the entity (using hook_entity_type_alter) or its individual fields (using hook_entity_bundle_field_info_alter). There are a number of different constraint classes already defined (UniqueField, Regex, etc.), or you could create your own.

This is better than adding validation on the node edit form, for example, since it will work anytime an entity is saved, such as when creating one programmatically.

For example:

 * Implements hook_entity_bundle_field_info_alter().

function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() !== 'node')
  if ($bundle !== 'page')

  /** @var FieldConfig $field */
  $field = $fields['field_custom_identifier'];

  // See the UniqueFieldConstraint class from Drupal core
  $field->addConstraint('UniqueField', [
    'message' => 'The custom identifier %value is already used by another page.',
Previous on Drupal
Mastodon Mastodon