skip to Main Content

I’m using Joi for validation in my Node.js project, and I’m trying to understand the difference between the custom() and external() methods. From the documentation, it seems like both methods are used for custom validation, but I can’t see any significant difference between them.

For example, if I want to trim a string value before validating it, I could use the external() method like this:

const schema = Joi.object({
  name: Joi.string().external((value, helpers) => value.trim()).required(),
});

Alternatively, I could use custom() like this:

const schema = Joi.object({
  name: Joi.string().custom((value, helpers) => value.trim()).required(),
});

In both cases, the name field is validated as a non-empty string with whitespace trimmed from both ends. So, what is the real difference between custom() and external()? When should I use one over the other?

I’d appreciate any insights or examples that can help clarify the differences between these two methods. Thank you!

2

Answers


  1. The difference is that external gives you the ability to do async processing whereas custom is only synchronous. There’s nothing to stop you using external to do synchronous stuff but it enables you to also do async.

    Hence the name “external” because you can use it to do processing for validation that happens externally on another service and therefore needs async.

    See docs for custom or external.

    Login or Signup to reply.
  2. If you look at the docs, there are subtle differences in both. The second argument helpers in the callback has a different shape and properties in both.

    But the major difference is that external() supports async operations and custom() does not. Here is what one of the contributors of the repo has to say on this:

    I am unlikely to ever support async functions outside of external() because that requires the entire module and validate() to always be async and that’s not an option. This is why we have external() – to provide some level of async support without breaking the sync API. It is limited in what it can do.

    The relevant github dicsussion

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search