Json

Json

Validates that a value has valid JSON syntax.

Applies toproperty or method
Options
ClassSymfony\Component\Validator\Constraints\Json
ValidatorSymfony\Component\Validator\Constraints\JsonValidator

Basic Usage

The Json constraint can be applied to a property or a “getter” method:

  • Annotations

    1. // src/Entity/Book.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Book
    5. {
    6. /**
    7. * @Assert\Json(
    8. * message = "You've entered an invalid Json."
    9. * )
    10. */
    11. private $chapters;
    12. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Book:
    3. properties:
    4. chapters:
    5. - Json:
    6. message: You've entered an invalid Json.
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Book">
    7. <property name="chapters">
    8. <constraint name="Json">
    9. <option name="message">You've entered an invalid Json.</option>
    10. </constraint>
    11. </property>
    12. </class>
    13. </constraint-mapping>
  • PHP

    1. // src/Entity/Book.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Book
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('chapters', new Assert\Json([
    10. 'message' => 'You\'ve entered an invalid Json.',
    11. ]));
    12. }
    13. }

Options

message

type: string default: This value should be valid JSON.

This message is shown if the underlying data is not a valid JSON value.

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.