Mick
Mick

Reputation: 31919

Validation on a pre-populated form field

To set a default value in a form field in symfony2, I use the rel attribute combined with jQuery as beautifully explained here:

    $builder->add('title', 'text', array(
        'attr'=> array(
            'class'=>'prepopulate',
            'rel'=>'Enter a title here...',
        )
    ));

This works perfectly and gives the following:


enter image description here


As you can see, the field is pre-populated with "Enter a title here...". If I validate the form as it is, validation does not take place as a default value is inserted (which makes sense).

I want to make sure the user customizes this field and does not just submit the form with the default value...

Is there a way to check if the field as the same value as the rel attribute?

Upvotes: 0

Views: 341

Answers (2)

Mick
Mick

Reputation: 31919

We can do this on the client side, and compare the rel attribute with the submitted data. If the value is the same, we clear the object:

$(function() {
    // When we submit the form
    $('form').submit(function() {

        //iterate over all the elements of the class "prepopulate"
        jQuery('.prepopulate').each(function(){

            //compare the values submitted vs rel attribute
            if( jQuery(this).val() == jQuery(this).attr('rel'))
                jQuery(this).val('');
        });
        return true; 
    });
});

Upvotes: 1

keyboardSmasher
keyboardSmasher

Reputation: 2811

Hmmm...

You could try this in your entity's annotation:

@Assert\Regex("/^(?!Enter a title here\.\.\.)/")

or even better:

/**
 * @Assert\Regex(
 *     pattern="/^Enter a title here\.\.\.$/",
 *     match=false,
 *     message="Please enter a title."
 * )
 */

Upvotes: 1

Related Questions