0
votes

Today I found a very interesting middleware to use for validation of the body via HTTP request. I am talking about Joi. However I need to make an OR statement in order to validate one field.

My code:

const { celebrate, Joi } = require('celebrate');
const joiObjectId = require('joi-objectid');
const constants = require('../../constants.js');

Joi.objectId = joiObjectId(Joi);

const validateBodySchema = celebrate({
  body: Joi.object().keys({
    name: Joi.string()
      .required()
      //.error(new Error('Name is a required field!'))
      .min(constants.MIN_CHAR_NAME)
      .max(constants.MAX_CHAR_NAME),
  
    address: Joi.string()
      .required()
      //.uri() -> This doesn't work because it checks whether the string is an uri valid AND an ip address. I need an OR here
      //.ip(),
    type: Joi.string()
      .required(),
  })
});

module.exports =  validateBodySchema;

After this I call it in app.js, on post method. The way it is written above it "works". But the errors that it throws are hardly readeble.

My problem is that the address have to be either an URL or an IP (ipv4) address. The way I did it is wrong because that's an and. Is there a way to do it?

Another problem is the error handling. If I uncomment the .error(new Error('...')) it throws one error saying AssertionError [ERR_ASSERTION]: value must be a joi validation error. On the internet I haven't found a solution yet. What do you think? Is there a way to do this or I just have to do it "classically"?

Thank you very much!

1
try making 2 validate body schemas.. one for url, other for ipv4.. does that work? - The Bomb Squad
yes bro, I fount the method! the idea is the one you said, but you can do it with the Joi. Check out my solution! and thank you ;) - user3001286

1 Answers

0
votes

I have found the solution! From the https://joi.dev/api/?v=17.3.0#alternativestryschemas you can find out how to do so:

address: Joi.alternatives().try(Joi.string().uri(),Joi.string().ip)

Instead of checking if the address is a string you verify two options: if it's a string and it's an uri or if it's a string and it's an ipv4.