dk80 dk80 - 1 year ago 128
PHP Question

Symfony2 form not validating required fields

I have a Symfony2 form that has required fields, which works fine in most browsers as the "required" attribute is on the inputs and so the user is unable to submit the form without filling in the field.

However, for the browsers that don't support the "required" attribute the form is submitted. This is causing a problem because when the form's isValid() function is called it returns true even though the required fields are empty.

Is this normal behaviour? I would assume there would be some server side checking of required fields during the form's handleRequest function but it doesn't seem to have any. If not is there a way to enable this?

Answer Source

You either need to check those things manually or you need to define validation constraints in your entity, to enable automatic validation.

If Symfony doesn't now what to check, it can do the validation.

Here's an example from the documentation linked above.

// src/AppBundle/Entity/Author.php

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

class Author
     * @Assert\NotBlank()
    public $name;

With this Constraint you're telling Symfony, that the name field mustn't be empty. So if the field will be submitted empty, the form validation will fail.

Never trust client side validation, since those can be modified and invalidated easily

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download