You can create a custom constraint by extending the base constraint class,
Constraint.
As an example you're going to create a simple validator that checks if a string
contains only alphanumeric characters.

The @Annotation annotation is necessary for this new constraint in
order to make it available for use in classes via annotations.
Options for your constraint are represented as public properties on the
constraint class.

As you can see, a constraint class is fairly minimal. The actual validation is
performed by another "constraint validator" class. The constraint validator
class is specified by the constraint's validatedBy() method, which
includes some simple default logic:

1
2
3
4
5

// in the base Symfony\Component\Validator\Constraint classpublicfunctionvalidatedBy(){returnget_class($this).'Validator';}

In other words, if you create a custom Constraint (e.g. MyConstraint),
Symfony will automatically look for another class, MyConstraintValidator
when actually performing the validation.

The validator class is also simple, and only has one required method validate():

Inside validate, you don't need to return a value. Instead, you add violations
to the validator's context property and a value will be considered valid
if it causes no violations. The buildViolation() method takes the error
message as its argument and returns an instance of
ConstraintViolationBuilderInterface.
The addViolation() method call finally adds the violation to the context.

If your constraint validator has dependencies, such as a database connection,
it will need to be configured as a service in the Dependency Injection
Container. This service must include the validator.constraint_validator
tag so that the validation system knows about it:

Now, when Symfony looks for the ContainsAlphanumericValidator validator, it will
load this service from the container.

Note

In earlier versions of Symfony, the tag required an alias key (usually
set to the class name). This alias is now optional, but if you define
it, your constraint's validatedBy() method must return the same value.