S
S
soho3502020-02-05 12:48:38
symfony
soho350, 2020-02-05 12:48:38

How to create custom validator in symfony?

How to create custom validator in symfony? I kind of read https://symfony.com/doc/4.4/validation/custom_cons... but I can't figure it out. I need validation to happen through an annotation like this.

/**
   * @Assert\NotBlank(message="Поле не должно быть пустым *")
   */
    private $name;

Let's write a simple validator if private $name is equal to 1 then display a message (message="Must not be equal to 1 *") . I think there is no point in throwing your validator here.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2020-02-05
@soho350

I kind of read https://symfony.com/doc/4.4/validation/custom_cons... but I can't figure it out.

/**
* @Annotation
*/
class ContainsAlphanumeric extends Constraint
{
public function validate($value, Constraint $constraint) {}
}

A little confusion occurred in a hurry: the annotation (constraint) is one thing, the validator is another, they are related, but these are two different things of the same system.
Constraint - in fact, an expression / annotation, according to which the validator will work. It takes in some parameters and contains the logic to what to apply - to a class or a class field.
We create our own constraint:
In our constraint, we plan that we will be able to pass some additional parameter размер, and if we don’t pass it, then its value will be 55 (well, that’s how we want it). Moreover, this will not apply to the field that we are validating, but to the constraint, that is, what it will give to the validator. Well, for example, age or a certain ping, whatever, in general, focusing on which validator will apply some logic.
/**
 * @Annotation
 */
final class AnyConstraint
{
    /**
     * @Required
     * @var int
     */
    public $size = 55;

    /**
     * Вот тут мы укажем некий валидатор, тот класс, который и будет валидировать наше значение
     * Дял удобства он будет называться также + слово Validator, в нашем случае AnyConstraintValidator
     */
    public function validatedBy()
    {
        return \get_class($this).'Validator';
    }
}

We create the validator itself
, which we have already indicated above in the validatedBy () method
class AnyConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint): void
    {
        // Тут логика, при которой или все пройдет до return - все отлично
        // Или вообще исключение вывалится (если пришло чего-то не то)
        // Или (для чего и используется валидатор) создастся violation

        // например число в объекте больше того, которое мы указали в size (по дефолту если не указали: 55)
        if($value > $constraint->size) {
            $this->context->buildViolation('Тут пинг пришел вообще большой  —  такой нельзя, брат')
                ->setParameter('{{ string }}', $value)
                ->addViolation();
        }
    }
}

We use:
class AnyEntity
{
    /**

     * Если значение больше 55  — то не пройдет валидацию
     * @AnyConstraint(120)
     */
    protected $name;
}

In addition to everything, the constraint can specify what to apply to - to a method, a class, or a class variable
  • Through an annotation on the constraint class:@Target({"PROPERTY", "METHOD", "ANNOTATION"})
  • Through method overridden getTarget() method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question