DEV Community

Discussion on: Joi — awesome code validation for Node.js and Express

Collapse
 
yawaramin profile image
Yawar Amin

You would get the greatest benefit by using a static typechecker like TypeScript or Flow in combination with a dynamic validator like Joi or Ajv. It works roughly like this:

  • Define a static type
  • Define a validator function for that type, using Joi or Ajv as the underlying validation tool
  • Make the validator function return the input value cast to the static type (if validation succeeded) or the validation error (if validation failed)

For example:

interface Person {
  id: string;
  name: string;
}

const personValidator: Validator<Person> = Validator(
  Joi.object().keys({id: Joi.string(), name: Joi.string()}),
);

...

const result = personValidator.validate(personObj);
if (result instanceof ValidationError) {...}
else {
  // Now we know 100% that result is a valid Person with id and name
}
Enter fullscreen mode Exit fullscreen mode