PHPackages                             ecourier/gobl-validator - 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. ecourier/gobl-validator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

ecourier/gobl-validator
=======================

A PHP library for validating JSON documents against the official GOBL schemas.

1186PHPCI passing

Since Dec 4Pushed 5mo agoCompare

[ Source](https://github.com/utecca/php-gobl-validator)[ Packagist](https://packagist.org/packages/ecourier/gobl-validator)[ RSS](/packages/ecourier-gobl-validator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

PHP GOBL Validator
==================

[](#php-gobl-validator)

A PHP library for validating JSON against [GOBL](https://gobl.org) schemas without requiring the GOBL CLI.

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

[](#installation)

```
composer require ecourier/gobl-validator
```

Usage
-----

[](#usage)

The validator accepts both JSON strings and objects.

### Basic Validation

[](#basic-validation)

The `validate()` method auto-detects the schema from the `$schema` property in your data:

```
use Ecourier\GoblValidator\GoblValidator;

$validator = new GoblValidator();

// Validate a JSON string
$invoiceJson = '{"$schema": "https://gobl.org/draft-0/bill/invoice", ...}';
$validator->validate($invoiceJson);

// Validate an object
$invoiceObject = json_decode($invoiceJson);
$validator->validate($invoiceObject);
```

### Supported Root Schemas

[](#supported-root-schemas)

The validator supports these root document types:

- `envelope` - `https://gobl.org/draft-0/envelope`
- `invoice` - `https://gobl.org/draft-0/bill/invoice`
- `order` - `https://gobl.org/draft-0/bill/order`

### Validate Envelope

[](#validate-envelope)

Use `validateEnvelope()` to explicitly validate against the envelope schema:

```
$validator->validateEnvelope($envelopeJson);
```

Handling Validation Errors
--------------------------

[](#handling-validation-errors)

When validation fails, a `GoblValidationException` is thrown containing the validation error details.

### Using getFormattedErrors() (Recommended)

[](#using-getformattederrors-recommended)

The `getFormattedErrors()` method provides clean, user-friendly error messages:

```
use Ecourier\GoblValidator\GoblValidator;
use Ecourier\GoblValidator\Exceptions\GoblValidationException;
use Ecourier\GoblValidator\Exceptions\InvalidSchemaException;

$validator = new GoblValidator();

try {
    $validator->validate($data);
} catch (InvalidSchemaException $e) {
    // The $schema property is not a supported root schema
    echo $e->getMessage();
} catch (GoblValidationException $e) {
    // Get formatted errors as an associative array (path => messages)
    $errors = $e->getFormattedErrors();
    print_r($errors);
    // Example output:
    // [
    //     '/currency' => ['The value "INVALID" is not a valid option'],
    //     '/supplier/tax_id/country' => ['The value "XX" is not a valid option'],
    //     '/customer/tax_id/country' => ['The value "YY" is not a valid option'],
    // ]
}
```

**Benefits of `getFormattedErrors()`:**

- **Returns all errors** - Validates the entire document and returns all validation failures, not just the first one
- **Consolidates enum errors** - Country codes, currency codes, and similar enum-like schemas return a single meaningful error instead of hundreds of "const mismatch" messages
- **Filters false positives** - Removes misleading "Unknown properties" errors that can appear at ancestor paths when nested validation fails
- **Clean paths** - Uses JSON Pointer-style paths like `/customer/tax_id/country`

### Using Opis ErrorFormatter (Advanced)

[](#using-opis-errorformatter-advanced)

For more control over error formatting, you can use the raw `validationError` property with Opis's `ErrorFormatter`:

```
use Opis\JsonSchema\Errors\ErrorFormatter;

try {
    $validator->validate($data);
} catch (GoblValidationException $e) {
    if ($e->validationError) {
        $formatter = new ErrorFormatter();

        // Get errors as an associative array (path => errors)
        $errors = $formatter->format($e->validationError);

        // Or get a flat list of error messages
        $flatErrors = $formatter->formatFlat($e->validationError);

        // Get detailed error information
        $detailedErrors = $formatter->formatOutput($e->validationError, 'detailed');
    }
}
```

> **Note:** The raw `ErrorFormatter` will show all sub-errors including hundreds of individual "const mismatch" errors for enum-like fields. Use `getFormattedErrors()` for cleaner output.

Limitations
-----------

[](#limitations)

This library performs **JSON Schema validation only**. It does not replace the GOBL CLI or API for full document validation.

### What this library validates:

[](#what-this-library-validates)

- Required fields (e.g., `type`, `issue_date`, `currency`, `supplier`, `totals`)
- Data types (strings, numbers, arrays, objects)
- Field formats (UUIDs, dates, country codes, currency codes)
- Enum values (invoice types, tax categories)
- Unknown properties (typos like `customer2` instead of `customer`)

### What this library does NOT validate:

[](#what-this-library-does-not-validate)

- Business rules (e.g., customer required for standard invoices)
- Tax calculations (e.g., totals matching line sums)
- Regime-specific requirements (e.g., Spanish TicketBAI, French Factur-X)
- Addon-specific validation rules
- Cross-field validation logic

For complete validation including business rules, use the [GOBL CLI](https://docs.gobl.org/quick-start/cli) or the GOBL API.

This library is ideal for:

- Quick structural validation in PHP applications
- Unit testing generated GOBL documents
- Catching common errors before sending to GOBL

GOBL Version
------------

[](#gobl-version)

The bundled schemas are derived from GOBL version:

```
echo GoblValidator::$GOBL_VERSION; // e.g., "0.303.0"
```

License
-------

[](#license)

This library is licensed under the MIT License.

The bundled GOBL schemas (in the `schemas/` directory) are © [Invopop Ltd](https://invopop.com) and licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). See the [GOBL repository](https://github.com/invopop/gobl) for more information.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance49

Moderate activity, may be stable

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/b81390d6fa3106520fc3654ac28a0035ca988356c5ec6f65624f2101de3b24e2?d=identicon)[Alberthaff](/maintainers/Alberthaff)

---

Top Contributors

[![alberthaff](https://avatars.githubusercontent.com/u/3864165?v=4)](https://github.com/alberthaff "alberthaff (1 commits)")

### Embed Badge

![Health badge](/badges/ecourier-gobl-validator/health.svg)

```
[![Health](https://phpackages.com/badges/ecourier-gobl-validator/health.svg)](https://phpackages.com/packages/ecourier-gobl-validator)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

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