ibram
ibram

Reputation: 140

Combine repeated property constraints in one Symfony custom validator

I have an application which has differtent entities with a password property. At the moment each entity has a repeated group of property constraints for the password property:

<?php
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
     // ...
     $metadata->addPropertyConstraint('password', new Length(...);
     $metadata->addPropertyConstraint('password', new NotBlank(...);
     $metadata->addPropertyConstraint('password', new Custom1(...);
     $metadata->addPropertyConstraint('password', new Custom2(...);
     // ...
}

I would like to have a custom validator "PasswordValidator" which "groups" all the different constraints as mentioned above. In that case, I only need to add one property constraint to each password property.

Like this:

<?php
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
     // ...
     $metadata->addPropertyConstraint('password', new MyCustomPassword(...);
     // ...
}

Any ideas?

Upvotes: 2

Views: 872

Answers (1)

kix
kix

Reputation: 3319

You need to use the All Symfony2 built-in constraint: http://symfony.com/doc/current/reference/constraints/All.html

Basically, that's how it should look in your case:

<?php
use Symfony\Component\Validator\Constraints as Assert;

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
     // ...
     $metadata->addPropertyConstraint(
        'password', 
        new Assert\All(
            new Assert\Length(...),
            new Assert\NotBlank(...),
            new Assert\Custom1(...),
            new Assert\Custom2(...)
        )
     );

Upvotes: 1

Related Questions