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
The difference is that
external
gives you the ability to do async processing whereascustom
is only synchronous. There’s nothing to stop you usingexternal
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.
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 andcustom()
does not. Here is what one of the contributors of the repo has to say on this:The relevant github dicsussion