Custom Validators on Validation Groups in Symfony2.

If you are using validation groups and have created a custom validator, you will want to use it in your validation group, however its a bit different from how you would apply validators in the entity, and quite similar in-fact to how you define services.

Its similar to how you define services because you have 2 root nodes, first somewhat like services.yml’s parameters line, in this instance called ‘namespaces’, the second part matches the entities name which the validator will be applied to.

Starting out, your validator.yml file probably looks like this:

This is an example taken from my AttachmentBundle, which you can find here.

Now, when we have a custom validator, in this case, some validators to check a users quota on file uploads etc, we need to set a namespace for our custom validators, with the namespace parameter, and then reference that namespace below followed by our custom validator.

The name of the validator must be wrapped in double quotes so that Symfony2 is aware that this is using a custom validator, inside of which we first start the namespace, and secondly the validator alias.

We define the alias of our validator in our services.yml like so:

Leave a Reply