PHPackages                             joipolloi/json-validation-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. joipolloi/json-validation-bundle

ActiveSymfony-bundle[Validation &amp; Sanitization](/categories/validation)

joipolloi/json-validation-bundle
================================

This bundle provides a way to validate JSON passed to a request against a schema

v1.0.3(8y ago)41.1k6[1 issues](https://github.com/joipolloi/json-validation-bundle/issues)MITPHP

Since May 9Pushed 3y ago6 watchersCompare

[ Source](https://github.com/joipolloi/json-validation-bundle)[ Packagist](https://packagist.org/packages/joipolloi/json-validation-bundle)[ RSS](/packages/joipolloi-json-validation-bundle/feed)WikiDiscussions master Synced 6d ago

READMEChangelogDependencies (4)Versions (7)Used By (0)

JSON Validation Bundle
======================

[](#json-validation-bundle)

[![Build Status](https://camo.githubusercontent.com/0561620cfdf7b1b93d91a2f3a7729988c36fc2faeabca606112deb2237778fd8/68747470733a2f2f6170692e7472617669732d63692e6f72672f6a6f69706f6c6c6f692f6a736f6e2d76616c69646174696f6e2d62756e646c652e737667)](https://travis-ci.org/joipolloi/json-validation-bundle)

A Symfony bundle that provides an annotation to validate JSON passed to a controller action against a schema.

Usage
-----

[](#usage)

When creating a controller method that accepts JSON as input (e.g. a POST method), put the `@ValidateJson` annotation on your action and point to the schema to validate against.

```
use JoiPolloi\Bundle\JsonValidationBundle\Annotation\ValidateJson

class MyController
{
    /**
     * @ValidateJson("@MyBundle/Resources/schema/action-schema.json")
     */
    public function myAction()
    {
        // ...
    }
}
```

Now any time the action is called, the passed JSON will be validated against the schema. If there are no validation errors, the action will execute as normal. If there are errors then a 400 (bad request) response will be returned.

Installation
------------

[](#installation)

Use composer: `composer require joipolloi/json-validation-bundle`

Open `AppKernel.php` in your Symfony project:

```
$bundles = array(
    // ...
    new JoiPolloi\Bundle\JsonValidationBundle\JsonValidationBundle(),
    // ...
);
```

Configuration
-------------

[](#configuration)

The only configuration option is whether to enable the application/problem+json event listener. This is described in detail below, it defaults to off, but can be enabled with the following configuration in your config.yml:

```
joipolloi_jsonvalidation:
    enable_problemjson_listener: true
```

Details
-------

[](#details)

Behind the scenes the bundle registers an event listener on the `kernel.controller` event that will validate the request content (i.e. `$request->getContent();`) against a JSON schema using the [justinrainbow/json-schema](https://github.com/justinrainbow/json-schema) library.

If there is an issue locating the JSON schema, decoding the JSON, decoding the JSON schema or validating against the JSON, a [JsonValidationException](Exception/JsonValidationException.php) (which extends BadRequestHttpException) is thrown with an error message.

Options
-------

[](#options)

### Getting the valid JSON

[](#getting-the-valid-json)

In order to save time and processing, you can get the validated JSON as an object by getting the `validJson` attribute on a request, or by putting `$validJson` as an argument to your action:

```
/**
 * @ValidateJson("@MyBundle/Resources/schema/action-schema.json")
 */
public function myAction(Request $request, $validJson)
{
    // $request->attributes->get('validJson') === $validJson
}
```

If you want the decoded JSON as an associative array or use the [Symfony form component](http://symfony.com/doc/current/forms.html), type hint `$validJson` as an array:

```
/**
 * @ValidateJson("@MyBundle/Resources/schema/action-schema.json")
 */
public function myAction(array $validJson)
{
    $form = $this->createForm(MyFormType::class);
    $form->submit($validJson);

    if ($form->isValid()) {
        // ...
    }
}
```

This does incur a slight performance overhead versus getting an object as the JSON needs to be decoded twice: once to validate against the JSON schema and again as an associative array. If your JSON is large but only a single level deep then you may get better performance by just casting to an array:

```
public function myAction($validJson)
{
    // ...
    $form->submit((array)$validJson);
}
```

### Specifying the HTTP methods to validate upon

[](#specifying-the-http-methods-to-validate-upon)

If your controller action listens on multiple HTTP methods (e.g. PUT and POST) and you only want to validate the JSON on one of them, you can use the `methods` parameter to the annotation:

```
/**
 * @ValidateJson("@MyBundle/Resources/schema/action-schema.json", methods={"POST"})
 */
public function myAction(Request $request, $validJson = null)
{
    if ($request->isMethod('POST')) {
        // $validJson !== null
    }
}
```

### Allowing for empty as a valid value

[](#allowing-for-empty-as-a-valid-value)

If for some reason you want to allow empty content to also be valid, use the `emptyIsValid` parameter to the annotation:

```
/**
 * @ValidateJson("@MyBundle/Resources/schema/action-schema.json", emptyIsValid=true)
 */
public function myAction($validJson = null)
{
    // ...
}
```

Note that only empty request content will be classed as valid; if empty but syntactically valid JSON is passed, this will still be validated against the schema (i.e. "{}" will not be counted as empty).

application/problem+json responses
----------------------------------

[](#applicationproblemjson-responses)

An exception listener is included within the bundle that can send an `application/problem+json` response as detailed in [RFC 7807](https://tools.ietf.org/html/rfc7807). The listener is turned off by default to allow for your own application to handle the exception but can be turned on with configuration in your config.yml file:

```
joipolloi_jsonvalidation:
    enable_problemjson_listener: true
```

If the listener is disabled, a 400 bad request exception is thrown and caught as per your application. If turned on and there is a problem decoding or validating the JSON, a response might look like:

```
{
    "status": 400,
    "title": "Unable to parse\/validate JSON",
    "detail": "There was a problem with the JSON that was sent with the request",
    "errors": [
        {
            "message": "[4] Syntax error"
        }
    ]
}
```

The "errors" key will be an array of at least one error. Each error will be an object with at least a "message" key, but may additionally have "constraint", "pointer" and "property" keys with useful information.

While errors within this array should be safe to send back to the client, there may be some information leakage with regards paths - either to the schema or referenced files. If in doubt, disable the listener and roll your own to have more control.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance15

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~44 days

Recently: every ~56 days

Total

6

Last Release

3070d ago

Major Versions

v0.2 → v1.02017-05-10

### Community

Maintainers

![](https://www.gravatar.com/avatar/89defbd67472162954e32f0a86de709bdfb7d9ab28834bfbea7d47cc5dca61e7?d=identicon)[joipolloi](/maintainers/joipolloi)

---

Top Contributors

[![johnnoel](https://avatars.githubusercontent.com/u/1096330?v=4)](https://github.com/johnnoel "johnnoel (23 commits)")

---

Tags

bundlejsonjson-schemajson-validationphpsymfonysymfony-bundle

### Embed Badge

![Health badge](/badges/joipolloi-json-validation-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/joipolloi-json-validation-bundle/health.svg)](https://phpackages.com/packages/joipolloi-json-validation-bundle)
```

###  Alternatives

[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.0M60](/packages/spatie-laravel-honeypot)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[illuminate/validation

The Illuminate Validation package.

18936.7M1.4k](/packages/illuminate-validation)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[netgen/layouts-core

Netgen Layouts enables you to build and manage complex web pages in a simpler way and with less coding. This is the core of Netgen Layouts, its heart and soul.

3689.4k10](/packages/netgen-layouts-core)[cuyz/valinor-bundle

Symfony integration of `cuyz/valinor` — a library that helps to map any input into a strongly-typed value object structure.

51215.0k2](/packages/cuyz-valinor-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
