Part # 9 Data Validation with Symfony2 Forms

How to validate data with Symfony forms, define validation rules and use twig as template

[Back to Learn Symfony 2]

Now that we know how to create Forms with Symfony 2 let's see hos to validate sumbmitted data through these forms or how to use sf2 validators. We will define validation rules for our entities and validate data in the Controller.

Define Validation Rules for an Entity

There are two ways to validate fields in Symfony 2

  • By defining validation rules with Yaml, PHP, XML or Annotations
  • Using validator service in our Controllers via dependency injection

Open the Car.php entity and add a new namespace called Assert

use Symfony\Component\Validator\Constraints as Assert;

These are the restrictions:

  • model, color and year should not be empty
  • model should be between 3 and 15 characters (MinLength and MaxLength)
  • year should be between 1950 and 2012

Let's see how to do this with annotations to concerned properties

* @var string $model
* @Assert\NotBlank(message="Model must not be empty")
* @Assert\MinLength(
* limit=3,
* message="Model should have at least {{ limit }} characters."
* )
* @Assert\MaxLength(15)
* @ORM\Column(name="model", type="string", length=255)
private $model;

* @var string $color
* @Assert\NotBlank(message="Color must not be empty")
* @ORM\Column(name="color", type="string", length=255)
private $color;

* @var integer $year
* @Assert\NotBlank(message="Year must not be empty")
* @Assert\Min(limit = "1950", message = "The min value for year is 1950")
* @Assert\Max(limit = "2012", message = "The max value for year is 2012")
* @ORM\Column(name="year", type="integer")
private $year;


The error message will be displayed in the twig tag form_errors:

{{ form_errors(form.model) }}

[Back to Learn Symfony 2]