# Symfony - Validation ###### tags: `Symfony` `gobelins` ## Initialisation ```composer composer require symfony/validator doctrine/annotations ``` ## Contraintes ```php class NotBlank extends Constraint { const IS_BLANK_ERROR = 'c1051bb4-d103-4f74-8988-acbcafc7fdc3'; protected static $errorNames = [ self::IS_BLANK_ERROR => 'IS_BLANK_ERROR', ]; public $message = 'This value should not be blank.'; public $allowNull = false; } ``` Ci-dessus un exemple de contrainte native. Il est possible de la modifier, notament pour customiser le message d'erreur de la contrainte. ## Ajouter des contraintes ### Annotations ```php // src/Entity/Author.php namespace App\Entity; // ... use Symfony\Component\Validator\Constraints as Assert; class Author { /** * @Assert\NotBlank */ private $name; } ``` ```php // src/Entity/Author.php namespace App\Entity; // ... use Symfony\Component\Validator\Constraints as Assert; class Author { /** * @Assert\Choice( * choices = { "fiction", "non-fiction" }, * message = "Choose a valid genre." * ) */ private $genre; // ... } ``` ### Yaml ```yaml # config/validator/validation.yaml App\Entity\Author: properties: name: - NotBlank: ~ ``` ## Valider des données ```php // ... use App\Entity\Author; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Validator\Validator\ValidatorInterface; // ... public function author(ValidatorInterface $validator) { $author = new Author(); $errors = $validator->validate($author); if (count($errors) > 0) { $errorsString = (string) $errors; return new Response($errorsString); } return new Response('The author is valid! Yes!'); } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up