How to create a custom constraint in Symfony?

by cortez.connelly , in category: PHP Frameworks , a year ago

How to create a custom constraint in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year ago

@cortez.connelly 

To create a custom constraint in Symfony, you need to follow these steps:

  1. Create a new class that extends SymfonyComponentValidatorConstraint. For example:
 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. Create a new class that implements SymfonyComponentValidatorConstraintValidatorInterface. This class will be responsible for validating the value of the custom constraint. For example:
 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. Register the constraint and the validator as services in your Symfony application. For example:
1
2
3
4
5
6
services:
    AppValidatorConstraintsCustomConstraint:
        tags:
            - { name: validator.constraint_validator, alias: custom }

    AppValidatorConstraintsCustomConstraintValidator: ~


  1. Use the custom constraint in your form or entity validation annotations, like any other Symfony constraint. For example:
 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.