Custom validator for checking if fields match I have two fields, value and copy that I'm trying to do some custom validation on to make sure they roughly match each other.

So far in my module I have this:

function HOOK_entity_bundle_field_info_alter(&amp;$fields, EntityTypeInterface $entity_type, $bundle)
{
    if(!empty($fields['field_value']) &amp;&amp; !empty($fields['field_copy']))
    {
        $fields['field_copy']-&gt;addConstraint('CopyMatchesValue');
        $fields['field_value']-&gt;addConstraint('CopyMatchesValue');
    }
}


A constraint

&lt;?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that value matches copy
 *
 * @Constraint(
 *   id = "CopyMatchesValue",
 *   label = @Translation("Copy Matches Value", context = "Validation"),
 * )
 */
class CopyMatchesValue extends Constraint
{
    // The message that will be shown if the format is incorrect.
    public $copyValueMismatch = 'The value does not look like it matches the copy.';
}


And a validator

&lt;?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the CopyMatchesValue constraint.
 */
class CopyMatchesValueValidator extends ConstraintValidator
{
  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint)
  {

      foreach ($items as $key =&gt; $item) {
          var_dump($item-&gt;value);
      }
      exit;

      // do some processing to make sure they match

      $this-&gt;context-&gt;addViolation();
    }
  }
}


I was expecting $items to have both fields I added the constraint to, but that doesn't seem to be the case.

How can I pass two fields to one validator so that I can validate them against each other?
I'm not sure if constraints is the best way to go when you need access to two fields. In your form alter, could you add a custom validation method? That way you would have access to array &amp;$form, FormStateInterface $form_state giving you access to all fields. 

$form['#validate'][] = 'my_test_validate';


And then your validation function...

/**
 * {@inheritdoc}
 */
function my_test_validate(array &amp;$form, FormStateInterface $form_state) {
  // Do what you need to do here...
}