How to use RegexConstraint with field? I'm defining a base field for my custom content entity:

$fields['machine_name'] = BaseFieldDefinition::create('string')
  -&gt;setLabel(t('Machine name'))
  -&gt;addConstraint('UniqueField')
  -&gt;addConstraint('Regex', ['pattern' =&gt; '[^a-z0-9_]+'])
  -&gt;setTranslatable(false)
  -&gt;setRequired(true);


However RegexValidator throws UnexpectedTypeException complaining that passed value is of type FieldItemList. This is obvious since in Drupal 8 even single value fields are lists (with one item).

So how can I use Regex validator with entity fields? Or do I have to write my own regex validator that will handle FieldItemLists?
You do not need to create your own Validator. Instead, use setPropertyConstraints instead of addConstraint to attach the Regex validator to the individual property of the field rather than the FieldItemList. For a string field, add the constraint to &quot;value.&quot; For a link field, you may want to add it to &quot;URI,&quot; etc. Here is an example:
-&gt;setPropertyConstraints(
  'value', ['Regex' =&gt; [
    'pattern' =&gt; '/^[0-9]+$/',
    'message' =&gt; t('Please use numbers only in the blah field.'),
  ]]
);