You are here

public function ValidJSONConstraintValidator::validate in JSON Field 8

File

src/Plugin/Validation/Constraint/ValidJSONConstraintValidator.php, line 42

Class

ValidJSONConstraintValidator
Checks if JSON values are valid.

Namespace

Drupal\json_field\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {

  // Empty should be handled by the field settings.
  if (empty($value->value)) {
    return;
  }
  try {
    $this->serializer
      ->decode($value->value, 'json');
  } catch (\Exception $e) {

    // Add a constraint violation with the `json_decode` message on failure.
    $this->context
      ->addViolation($constraint->message, [
      '@error' => $e
        ->getMessage(),
    ]);
  }
}