Module Development

Entity Validation API for Drupal 8, 9, and 10

Drupal includes the Symfony Validator component, and provides an Entity Validation API to assist in validating the values of fields on an entity. By using the Entity Validation API you can ensure that you're validation logic is applied to Entity CRUD operations regardless of how they are triggered. Whether editing an Entity via a Form API form, or creating a new Entity via the REST API, the same validation code will be used.

Using the Entity Validation API in order to validate the value of a field on an entity requires:

  • Defining (or choosing) a constraint plugin
  • Defining (or choosing) a validation plugin
  • Adding the constraint to the field definition

In this tutorial, we'll look at how this Validation API works and how it can be used in custom code to ensure our entities have properly constructed values. We'll look at how this validation works in Drupal core and how we can add our own additional constraints. We'll also see how to work with the error messages returned from the validator when our entity doesn't pass validation.