1

My question is related to symfony validator component. I don't use forms. And I want to move validation rules for each entity to separated class (like AuthorVlidator, BookingValidator etc.). How can I move it to separated classes and define rules?

Thanks.

2
  • If I understand correctly, you are looking for Validation Groups Commented Jun 10, 2016 at 8:39
  • Simply inject the validation component into your Validator classes and have at it. No need to get fancy. Commented Jun 10, 2016 at 10:21

1 Answer 1

2

Why would you like to move it to separated classes? With annotations it pretty easy to use it.

It's not a good idea to do it, but if you really want to do it in other classes, you could add this method in each classes that you want to validate:

class YourObject
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        YourObjectValidator::validate($this, $metadata);
    }
}

And:

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;

class YourObjectValidator
{
    public static function validate(YourObject $object, ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());
    }
}

If you want separate this logic for add validation depending on properties value, it's not the proper way to do it. You should read the doc, callback could be a solution.

Sign up to request clarification or add additional context in comments.

Comments

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.