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!