Skip to content

Missing helper.error() method parameter type definition #2874

@dariosn85

Description

@dariosn85

Support plan

  • is this issue currently blocking your project? (yes/no): yes
  • is this issue affecting a production system? (yes/no): yes

Context

  • node version: 16.16.0
  • module version with issue: 17.7.0
  • last module version without issue: unknown
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone
  • any other relevant information:

What are you trying to achieve or the steps to reproduce?

In case of any.custom you can use helpers.error() to create validation error. In the TypeScript file (.d.ts), the definition says that error takes 2 parameters, code and optional local context.

    interface CustomHelpers<V = any> {
        ...
        error: (code: string, local?: Context) => ErrorReport;
        ...
    }

From the code (lib/validator.js file) we can see that error method actually takes 3 parameters (code, local and localState):

    const createError = (code, local, localState) => schema.$_createError(code, value, local, localState || state, prefs);
    const helpers = {
        ...
        error: createError,
        ...
    };

What was the result you got?

To have localContext as a parameter it would be useful for example in case if you are doing some custom validation on root level (root object), and you would like to get correct path and label in final error. My case was limiting the duration between from and to dates to maximum of 90 days. See the following example:

const joi = require('joi')

const schema = joi
  .object({
    from: joi.date().iso().required(),
    to: joi.date().iso().required().greater(joi.ref('from')),
  })
  .custom((value, helpers) => {
    const { from, to } = value;
    const diff = (to.getTime() - from.getTime()) / 86400000;

    if (diff > 90) {
      return helpers.error(`err.invalidDateRange`);
    }

    return value;
  })
  .message({
    'err.invalidDateRange': `Invalid date range...`,
  });

const { error } = schema.validate({
  from: new Date(2022, 1, 1),
  to: new Date(2023, 1, 1),
});

console.log(error.details[0].context.label); // <- Problem: we get "value"
console.log(error.details[0].path); // <- Problem: we get [] (empty array)

What result did you expect?

In case if it would be allowed to specify localState we could provide local state with path (parameter that we are validating).

      ...

      helpers.error(`err.invalidDateRange`, undefined, {
        ...helpers.state,
        path: ['toDate'],
      });

      ...

console.log(error.details[0].context.label); // <- we get "toDate"
console.log(error.details[0].path); // <- we get ["toDate"]

Metadata

Metadata

Assignees

Labels

supportQuestions, discussions, and general support

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions