2

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?

1 Answer 1

1

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(...)
        )
     );
Sign up to request clarification or add additional context in comments.

2 Comments

I want to seperate these 4 constraints from the entity, this is is just another way of coding my snippet.
Well, then you could implement your own constraint that would be very similar to the given All constraint except that its members will be hardcoded. I personally think that it wouldn't make your code more readable, but the opposite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.