Symfony2 custom validation constraints

The Symfony2 framework comes with a really nice validation library and on top of the built in constraints that you can use you also have the ability to add your own custom constraints to perform any other validation checks you need to do.

The Cookbook has an article on how to create such a custom constraint, but unfortunately, as has happened a few times with the Symfony2 documentation, it misses out some fundamental and sometimes rather obscure step in order to get it working.

The problem is, it doesn’t tell you where to put the files. That leaves two options – either you have somewhere they need to be in order for Symfony to find them, or you need to fell Symfony where they are.

After hours of digging around, we eventually found the answer – in your validation.yml file you need to register the namespace and then reference that name when you call the validation rules.

Start by registering the namespace at the top of your validation.yml file.

namespaces:
  myValidator: Acme\ExampleBundle\Validator\

Lets say you have added a custom validation constraint called Postcode. When you want to invoke that from your validation rules, you need to reference the namespace you have just created.

postcode:
    - myValidator:Postcode: ~

You can then use this namespace with your custom validation rules, place them in the appropriate directory (in this case src/ExampleBundle/Validator, but you can store them somewhere else if you change the namespace – remember that Symfony2 will extract the path from the namespace).

Timeline

Newsletter

Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.

Metadata

Tags: , , , , ,

This entry was posted on Friday, June 15th, 2012 at 11:56 am and is filed under Limited, Programming. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.