FOSUserBundle - Validation for username, password or email fields

M. Winterinho picture M. Winterinho · May 23, 2013 · Viewed 16.4k times · Source

In the FOUserBundle, I would like to be able to change the validation settings for minimum length, maximum length and not blank on fields such as username and password.

I was able to put some validation via @Assert on my custom fields, but now I am wondering how I could change the username validation for the FOSUserBundle?

These fields are generated automatically, so I can't add them to my User entity... and by default, it allows characters like {^| etc... which don't look good.

Answer

Nicolai Fröhlich picture Nicolai Fröhlich · May 23, 2013

You can overwrite the default settings by creating a new validation file in your bundle. This is bundle inheritance. Just copy (not cut).

FOSUserBundle/Resources/config/validation/orm.xml to YourBundle/Resources/config/validation/orm.xml.

(couchdb.xml, mongodb.xml, propel.xml respectively)

and adjust it to your needs. Change the class name, then add your constraints:

<class name="Vendor\YourBundle\Model\User">

    <property name="username">
        <!-- minimum length for username -->
        <constraint name="MinLength">
            <option name="limit">3</option>
            <option name="message">Your name must have at least {{ limit }} characters.</option>
        </constraint>
        <!-- custom constraint -->
        <constraint name="Acme\DemoBundle\Validator\Constraints\ContainsAlphanumeric" />
    </property>

    <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
        <option name="fields">usernameCanonical</option>
        <option name="errorPath">username</option>
        <option name="message">fos_user.username.already_used</option>
        <option name="groups">
            <value>Registration</value>
            <value>Profile</value>
        </option>
    </constraint>

    <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
        <option name="fields">emailCanonical</option>
        <option name="errorPath">email</option>
        <option name="message">fos_user.email.already_used</option>
        <option name="groups">
            <value>Registration</value>
            <value>Profile</value>
        </option>
    </constraint>
</class>

Read more about which constraints are available (and how to use them with xml configuration ) in the Validation Constraints Reference.