Custom validation in Joi is not returning error message

36 views Asked by At

I was trying to make the email unique using Joi validation by making custom validation function checking if it exists in the database and even though the

console.log(user);

is working, I'm not getting the validation error of the custom function I made.

this is my code

const isUniqueEmail = async (value, helpers) => {
  const user = await User.query().where("email", value).first();

  if (user) {
    console.log(user);
    return helpers.error("any.invalid");
  }

  return value;
};

I got this return helpers.error("any.invalid"); from Joi docs but it's not working and this is my object

const videosSchema = Joi.object({
  channel_id: Joi.number().required().label("Channel Id"),
  email: Joi.string().required().custom(isUniqueEmail),
  title: Joi.string().required().min(5).max(50),
});

it's not giving me the error when the email is already used even though it's logging the user

But the other validations are working

1

There are 1 answers

0
Abned On

As documentation said:

any.custom(method, [description]) Adds a custom validation function to execute arbitrary code where:

  • method - the custom (synchronous only) validation function using signature function(value, helpers)

In your case, isUniqueEmail is not synchronous. I suggest to move your validation in your business layer code.