json-schema icon indicating copy to clipboard operation
json-schema copied to clipboard

Validation stops on first error

Open dontub opened this issue 2 years ago • 6 comments

Currently the validation stops if an error occurs. https://github.com/opis/json-schema/blob/c48df6d7089a45f01e1c82432348f2d5976f9bfb/src/Schemas/ObjectSchema.php#L114 So if for example a required property is missing, the available properties are not validated at all. Actually we need to have all object properties/array items to be validated. Maybe it would make sense to have different maximum error limits:

  • Per leaf data (e.g. type is number, but a string is given. Then it makes sense to stop the validation for this data without checking further keywords like minimum.)
  • Per object properties/array items (this is already possible)
  • Overall

dontub avatar Jun 13 '22 08:06 dontub

For our project we are depending on this. (Not on the suggested error limits, though.) We'd like to avoid a custom fork so we would highly appreciate if a solution for this issue can be found.

Ping @sorinsarca :-)

dontub avatar Aug 09 '22 15:08 dontub

This code in ObjectSchema would solve the issue:

protected function applyKeywords(array $keywords, ValidationContext $context): ?ValidationError
{
    $errors = [];
    foreach ($keywords as $keyword) {
        if (null !== ($error = $keyword->validate($context, $this))) {
            $errors[] = $error;
        }
    }

    if ([] === $errors) {
        return null;
    }

    if (1 === \count($errors)) {
        return $errors[0];
    }

    /** @var Schema $schema */
    $schema = $context->schema();

    return new ValidationError(
        'schema',
        $schema,
        DataInfo::fromContext($context),
        'The data does not match the schema',
        ['data' => $context->currentData()],
        $errors
    );
}

The part

if (1 === \count($errors)) {
    return $errors[0];
}

isn't necessary, though if there's only one error the behavior is as before.

Edit: Changed error message to not contain {data} because Opis\JsonSchema\Errors\ErrorFormatter doesn't support \stdClass: https://github.com/opis/json-schema/blob/c48df6d7089a45f01e1c82432348f2d5976f9bfb/src/Errors/ErrorFormatter.php#L231 (Showing the whole JSON in the error message probably makes no sense in most cases...)

dontub avatar Aug 23 '22 09:08 dontub

I agree with @dontub.

Tried code and works as a breeze! :D

matapatos avatar Aug 31 '22 08:08 matapatos