Search code examples
javascripttypescriptvalidationjoi

how to handle errors from a custom validation with JOI?


I want set a custom error message for my custom validation with JOI, but this not work

 field: Joi.string()
.required()
.custom((value, helper) => {
  if (!isValidField(value)) {
    return helper.message({'any.custom': 'This value is Invalid'});
  }
  return value;
}),

Solution

  • I solved the problem with this code

    field: Joi.string()
    .required()
    .custom((value, helper) => {
      if (isValidField(value)) {
        return value;
      }
      return helper.message({ custom: 'This value is Invalid' });
    })
    

    found the answer on this link: https://github.com/sideway/joi/issues/2235