I’ve recently tried to modify the password constraints of FOSUserBundle. To my surprise I’ve discovered that this is a little bit tricky.
Before you start I would suggest taking a look at validation.xml
in the config
directory of FOSUserBundle There you’ll find all the pre-defined constraints. As you can see, there is a class named FOS\UserBundle\Form\Model\ChangePassword
. This is the data class, which is used in the change password form instead of the actual entity. So you have to change the password constraints on the User
as well as on the ChangePassword
class.
I have a bundle, which is extending FOSUserBundle, so I thought it is straight forward: Create a validation.xml
which is overwriting the original one and put my own constraints in there. Unfortunatley that doesn’t work, instead my own constraints will simply be added to the default ones. So how to get rid of them? The trick is to define your own validation group.
This is how my configuration for the ChangePassword
class looks like. The same goes for the User
class.
By default FOSUserBundle is using the ChangePassword group to validate the change password form. With some extra lines in config.yml
you can tell it to use a different one:
fos_user: change_password: form: validation_groups: [MyChangePassword, Default]
Now FOSUserBundle is using the MyChangePassword
validation group for validation. This is also working for other forms like registration or the user profile. Take a look at the class FOS\UserBundle\DependencyInjection\Configuration
and search for validation_groups
to find out more about the configuration.
Hello sir m trying to add custom validation in fos user bundle .. i have done all tricks but not well.
i wanna add some constraints on user registration form in my sonata admin .
like user name must 8 character
thanks
Take a look at the original validation.xml file from the FOSUserBundle. Copy the block for the
FOS\UserBundle\Model\User
class into your own validation.xml file and adapt the rules to match your requirements. Then change the validation group name from “Registration” to “MyRegistration”.In config.yml tell the bundle to use your validation group instead of the original one:
If you want your rules to be applied to the profile form too, then do the same with the “Profile” validation group. The config will be:
Haven’t testet this, but it should work.