ajv-validator / ajv

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
https://ajv.js.org
MIT License
13.74k stars 871 forks source link

Reporting custom errors from custom formats #119

Open epoberezkin opened 8 years ago

epoberezkin commented 8 years ago

Synchronous formats should assign to errors property of format validation function, asynchronous formats should throw exception (See #118)

HugoMuller commented 6 years ago

Hi,

first of all, thanks for the work you've done. This lib is great :D

Is this feature still in your roadmap?

With ajv@6.1.1, when an async custom format resolves whit false, the error contains the dataPath:

ajv.addFormat('custom', {
  async: true,
  type: 'string',
  validate: data => Promise.resolve(false)
});

const schema = {
  $async: true,
  properties: {
    foo: { type: 'string', format: 'custom' }
  }
};

ajv.compile(schema)({ foo: 'a' }); // => data.foo should match format "custom"

The validate method does not receive the dataPath, so when it rejects with a ValidationError, the dataPath is lost:

ajv.addFormat('custom', {
  async: true,
  type: 'string',
  validate: data => Promise.reject( new Ajv.ValidationError([{ message: 'oops' }]) )
});

const schema = { foo: { type: 'string', format: 'custom' } };

ajv.compile(schema)({ foo: 'a' }); // => dataundefined oops

Any chance of making a PR on this?

epoberezkin commented 6 years ago

I may be missing something but it seems to me that the problem you're describing is unrelated to this issue? Also, the schema should have $async: true in it...

HugoMuller commented 6 years ago

You're right, $async: true is missing in my example, but adding it does not solve the problem.

My example shows a custom format custom rejecting with a custom error oops. So it's related to to this issue, I think. Or maybe I misunderstand what "custom errors" stands for :(

epoberezkin commented 6 years ago

This issue is about supporting custom errors in synchronous custom formats. Currently it is not possible at all (and nobody ever asked for it).

You are describing a different problem here: some missing information in the custom error in async format. Please submit a separate issue.

okbeng03 commented 6 years ago

I want the feature that support custom errors in custom formats,especially when custom format function,only the error "should match format ***",can't explain more

silverwind commented 4 years ago

Synchronous formats should assign to errors property of format validation function

Assigning to a function seems so weird to me and it may be prone to race conditions too.

Why not let the format function throw/reject in both sync and async cases?

jgod commented 3 years ago

I want the feature that support custom errors in custom formats,especially when custom format function,only the error "should match format ***",can't explain more

Agreed

m00nk commented 3 years ago

any news?