title: How to add validators on the fly in Symfony2?
body: <p>I've a <code>password</code> form field (<strong>not</strong> mapped to <code>User</code> password) to be used in a change password form, along with two other (mapped) fields, <code>first</code> and <code>last</code>.</p>
  
  <p>I've to add validators on the fly: if value for <strong>password is blank then no validation</strong> should occur. Otherwise a new <strong><code>MinLength</code> and <code>MaxLength</code> validators should be added</strong>.</p>
  
  <p>Here is what i've done so far: create the repeated <code>password</code> field, add a <code>CallbackValidator</code> and <code>return</code> if <code>$form-&gt;getData()</code> is <code>null</code>.</p>
  
  <p><em><strong>Then, how can i add validators for minimum and maximum length to $field?</em></strong></p>
  
  <pre><code>    $builder = $this-&gt;createFormBuilder($user);
  
      $field = $builder-&gt;create('new_password', 'repeated',  array(
              'type'          =&gt; 'password',
              'first_name'    =&gt; 'Password',
              'second_name'   =&gt; 'Confirm password',
              'required'      =&gt; false,
              'property_path' =&gt; false // Not mapped to the entity password
          ));
  
      // Add a callback validator the the password field
      $field-&gt;addValidator(new Form\CallbackValidator(function($form) {
          $data = $form-&gt;getData();
  
          if(is_null($data)) return; // Field is blank
  
          // Here password is provided and match confirm, check min = 3 max = 10
  
      }));
  
      // Add fields to the form
      $form = $builder
          -&gt;add('first', 'text', array('required' =&gt; false)) // Mapped
          -&gt;add('last',  'text', array('required' =&gt; false)) // Mapped
          -&gt;add($field)                                      // Not mapped
          -&gt;getForm();
  </code></pre>