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:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.