@cortez.connelly
To create a custom constraint in Symfony, you need to follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
namespace AppValidatorConstraints; use SymfonyComponentValidatorConstraint; /** * @Annotation */ class CustomConstraint extends Constraint { public $message = 'My custom constraint message'; public function validatedBy() { return get_class($this).'Validator'; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
namespace AppValidatorConstraints; use SymfonyComponentValidatorConstraint; use SymfonyComponentValidatorConstraintValidator; class CustomConstraintValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { if ($value < 0) { $this->context->buildViolation($constraint->message) ->addViolation(); } } } |
1 2 3 4 5 6 |
services: AppValidatorConstraintsCustomConstraint: tags: - { name: validator.constraint_validator, alias: custom } AppValidatorConstraintsCustomConstraintValidator: ~ |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
namespace AppEntity; use AppValidatorConstraints as CustomAssert; use SymfonyComponentValidatorConstraints as Assert; class MyEntity { /** * @AssertNotBlank * @CustomAssertCustomConstraint */ private $myField; } |
That's it! Your custom constraint is now ready to use in your Symfony application.