How to perform entity validation on code level? I have an entity that has a field attached to it and the values that user types into the field has to be globally(website) unique(compared to other entities).

I have added validation to the entity form but what if I create this entity programmatically? How can I prevent the entity to be saved into the storage?

I've noticed there is a validate method in ContentEntityBase, though not in ConfigEntityBase.
Is this the place for it? If so, I could use some examples.
Fields have constraints defined on them and as everything is a field on an entity, that's that. See Comment::baseFieldDefinitions does -&gt;setConstraints(array('CommentName' =&gt; array()));. Then there's appropriate plugin in the Drupal\comment\Plugin\Validation\Constraint namespace in a class called CommentNameConstraint. The logic is in CommentNameConstraintValidator.

So the chain is


setConstraints in basedFieldDefinitions setting a list of plugin ids (CommentName) and their arguments (empty array in the example
A plugin in the Drupal\modulename\Plugin\Validation\Constraint namespace with the appropriate plugin id. The classname is not magic, the plugin id is what's important. Using the plugin id plus Constraint as classname seems to be best practice.
Whatever classname you picked in the previous step, append Validator to it, make it extend Symfony\Component\Validator\ConstraintValidator and put your validation logic in validate.