You are here

public static function JsonEditorWidget::validateJsonData in JSON Field 8

Check the submitted JSON against the configured JSON Schema.

Parameters

$element:

\Drupal\Core\Form\FormStateInterface $form_state:

File

src/Plugin/Field/FieldWidget/JsonEditorWidget.php, line 169

Class

JsonEditorWidget
Plugin implementation of the 'json_editor' widget.

Namespace

Drupal\json_field\Plugin\Field\FieldWidget

Code

public static function validateJsonData($element, FormStateInterface $form_state) {
  $hash = $element['#attributes']['data-json-editor'];
  $settings = $element['#attached']['drupalSettings']['json_field'][$hash];
  $json_schema = $settings['schema'];

  // Do not use Json::decode since it forces a return as Array.
  $data = json_decode($element['#value']);
  try {
    $schema = Schema::import(json_decode($json_schema));
    $schema
      ->in($data);
  } catch (\Exception $e) {
    $form_state
      ->setError($element, t('JSON Schema validation failed.'));
  }
}