I have various functions/methods that programmatically create entities (nodes). I just noticed that invalid data has been getting stored in the db though these functions (invalid in that it doesn't meet the rules defined for that field).

How do I validate the data before $entity->save()?

I have seen documentation saying that I simply need to do $entity->validate() and then count if there are any errors; but I have marked a few fields as required and then left them empty in my API function and $entity->validate()->count() is always 0.

What am I missing?

  • 1
    you need to create field constraints refer drupal.stackexchange.com/questions/294733/… Feb 1, 2021 at 11:08
  • @miststudent2011, thanks for the reply, but that post sounds a lot like how to add custom constraints. I do not have any custom constraints I want to add; I just want to validate against the existing ones. That being said, I am starting to get the idea that the constraints which fields do by default are only designed for form submission and not as "proper" constraints. Is this possible; and if so, wouldn't this be considered a bug in core?
    – liquidcms
    Feb 1, 2021 at 15:37

1 Answer 1


Looking the api it should be simple:

$violations = $entity->validate();
  if ($violations->count() > 0) {
    // Validation failed.
  • Yes, should be simple enough. Except that doesn't work.
    – liquidcms
    Feb 2, 2021 at 20:30
  • Have you tried to debug inside the validation function when you call it, to see where the logic doesn't work?
    – Giuseppe
    Feb 3, 2021 at 8:16

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.