FOSUserBundle icon indicating copy to clipboard operation
FOSUserBundle copied to clipboard

FOSUserBundle: How to override validations ?

Open nirav-programmer opened this issue 12 years ago • 12 comments

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

Any help ?

nirav-programmer avatar Jan 31 '13 22:01 nirav-programmer

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

mvrhov avatar Feb 01 '13 07:02 mvrhov

@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 ?

nirav-programmer avatar Feb 03 '13 22:02 nirav-programmer

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.

mvrhov avatar Feb 04 '13 07:02 mvrhov

@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

nirav-programmer avatar Feb 04 '13 22:02 nirav-programmer

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);
    }
}

Haehnchen avatar Apr 15 '13 12:04 Haehnchen

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.

dmb-dz avatar Jul 25 '13 11:07 dmb-dz

@dmb-dz :+1:

Sharom avatar Aug 21 '13 11:08 Sharom

:+1:

webdevilopers avatar Sep 23 '14 08:09 webdevilopers

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

jalpeshmakadia avatar Jul 17 '15 11:07 jalpeshmakadia

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.

jenniferleveaux avatar Jan 26 '16 10:01 jenniferleveaux

@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);

sbpro86 avatar Jan 10 '17 00:01 sbpro86

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.

heximcz avatar Apr 03 '17 15:04 heximcz