FriendsOfSymfony / FOSUserBundle

Provides user management for your Symfony project. Compatible with Doctrine ORM & ODM, and custom storages.
https://symfony.com/doc/master/bundles/FOSUserBundle/index.html
MIT License
3.25k stars 1.57k forks source link

FOSUserBundle: How to override validations ? #986

Open nirav-programmer opened 11 years ago

nirav-programmer commented 11 years ago

I want to override FOSUserBundle Validations and set New validations to my user entity's custom fields.

Any help ?

mvrhov commented 11 years ago

You can't override them. You have to use a different group. There is a closed! issue on symfony about that. symfony/symfony#3224

nirav-programmer commented 11 years ago

@mvrhov I check symfony#3224

Validation not working for me.

My Requirement.

I have some user related fields like first_name, last_name etc.

I extend UserBundle and create my own entry/user class and extend FosUser class.

On registration page I want to set validation for first_name.

What i need to do ?

mvrhov commented 11 years ago

Well if you only need to add them, then just create a validation for your model in the same validation groups and call it a day.

nirav-programmer commented 11 years ago

@mvrhov

I tried it but it's not working.

I explore lots of on net but i not found anything related to it.

If you have idea about it and if it's working for you then can you provide me example files... ? if possible.

Thanks

Haehnchen commented 11 years ago

i need to replace FOS\UserBundle\Resources\config\validation\orm.xml so just overwrite it on CompilerPass. not really nice but works for now

class OverwriteUserValidation implements CompilerPassInterface {

    public function process(ContainerBuilder $container) {

        if (!$container->hasParameter('fos_user.storage') OR !$container->hasParameter('validator.mapping.loader.xml_files_loader.mapping_files')) {
            return;
        }

        $storage = $container->getParameter('fos_user.storage');
        if ('custom' === $storage) {
            return;
        }

        $validationFile = __DIR__ . '/../../Resources/config/fos_validation/' . $storage . '.xml';

        if (!is_file($validationFile)) {
            throw new \RuntimeException();
        }

        $files = $container->getParameter('validator.mapping.loader.xml_files_loader.mapping_files');

        foreach ($files as $key => $file) {
            if ($this->endsWith(str_replace('\\', '/', $file), 'FOS/UserBundle/Resources/config/validation/orm.xml')) {
                $files[$key] = realpath($validationFile);
                $container->addResource(new FileResource($validationFile));
            }
        }

        $container->setParameter('validator.mapping.loader.xml_files_loader.mapping_files', $files);

    }

    private function endsWith($haystack, $needle) {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $needle);
    }
}
dmb-dz commented 11 years ago

I just overrode the default validation groups by providing them in config.yml (for the profile form):

fos_user:
    profile:
        validation_groups [Foo]

Works as expected when applying it to my User entity:

* @Assert\Regex(
*   pattern="/^\D+$/",
*   groups={"Foo"}
* )

Imho this should also work without having to override the bundle.

Sharom commented 11 years ago

@dmb-dz :+1:

webdevilopers commented 10 years ago

:+1:

jalpeshmakadia commented 9 years ago

You should add extra field in FOSUserBundle entity and orm. then after update schema with --force. And put validation in /friendsofsymfony/user-bundle/Resources/config/validation.xml

jenniferleveaux commented 8 years ago

If you are using validation groups, it won't work because in the FormFactory, FosUser creates a form with thoses groups : "Registration" and "Default". If you added a validation group in the setDefaultOptions(), it won't work. You have to use the "Registration" validaton group or, override the controller to add your validation group into the FormFactory Service or in the createForm() method.

selimb86 commented 7 years ago

@jenniferleveaux If I override the controller and add the validation group in the setDefaultOptions() it should work no ?

Here is how I create the form: $user = new User(); $form = $this->createForm(RegistrationAdminType::class, $user);

heximcz commented 7 years ago

AppBundle/Entity/User


...
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{

    /**
     * @Assert\Length(
     *     min=8,
     *     max=100,
     *     minMessage="user.password.short",
     *     groups={"Profile", "ResetPassword", "Registration", "ChangePassword"}
     * )
     * @Assert\Regex(
     *     pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,100}$/",
     *     message="user.password.difficulty",
     *     groups={"Profile", "ResetPassword", "Registration", "ChangePassword"}
     * )
     */
    protected $plainPassword;

...

and add to the - app/Resources/translations/validators.(language).yml

user:
    password:
        short: 'Password must be at least 8 characters long.'
        difficulty: 'Password must contain aA-zZ and number 0-9'

Pattern allow special chars too.