In foundation_anchor_menu_block module I needed to add a validation to a field in a block to ensure the entered value matches the regex allowed for an "id" HTML element attribute.
This is quite simple using Drupal 8 and Symfony Constraints / Validators:
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_entity_bundle_field_info_alter.
*/
function foundation_anchor_menu_block_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if ($entity_type->id() == 'block_content' && $bundle == 'famb_anchor' && !empty($fields['field_block_famb_anchor_id'])) {
$fields['field_block_famb_anchor_id']->setPropertyConstraints('value', [
'Regex' => [
'pattern' => '/^[A-Za-z]+[\w\-\:\.]*$/',
'message' => t('The ID must begin with a letter ([A-Za-z]) and may be followed by any number of letters ([A-Za-z]), digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").'),
],
]);
}
}
?>
GREAT article about that can be found here:
https://jigarius.com/blog/drupal-entity-validation-api
Module alternative: https://www.drupal.org/project/rfv
Also see:
https://www.drupal.org/docs/8/api/entity-api/entity-validation-api/prov…
https://blog.codeenigma.com/introduction-to-drupal-8-entity-validation-…
https://drupal.stackexchange.com/questions/202481/how-to-use-regexconst…
https://drupal.stackexchange.com/questions/226275/how-can-i-add-a-const…