Callback Constraint

Last updated on
21 August 2023

Use case:

add a Callback constraint to field_test, set callback to "\Drupal\mymodule\MyValidator::validate", save it.

"Drupal\mymodule\MyValidator::validate" also works. you can change the validate function name, validateA, validateB...

Here is the code example, :

namespace Drupal\mymodule;

use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * My validator callback.
 */
class MyValidator {

  /**
   * {@inheritdoc}
   */
  public static function validate(mixed $items, ExecutionContextInterface $context, mixed $payload): void{
    if (!$item = $items->first()) {
      return;
    }
	if(mb_strlen($item->value) < 3){
      $context->addViolation("The length is too low.");
	}	
  }
}

Help improve this page

Page status: No known problems

You can: