How to add custom validator function in Joi? How to add custom validator function in Joi? express express

How to add custom validator function in Joi?


Your custom method must be like this:

const method = (value, helpers) => {  // for example if the username value is (something) then it will throw an error with flowing message but it throws an error inside (value) object without error message. It should throw error inside the (error) object with a proper error message  if (value === "something") {    return helpers.error("any.invalid");  }  // Return the value unchanged  return value;};

Docs:

https://github.com/hapijs/joi/blob/master/API.md#anycustommethod-description

Output for value :

{ username: 'something' }

Output for error:

[Error [ValidationError]: "username" contains an invalid value] {  _original: { username: 'something' },  details: [    {      message: '"username" contains an invalid value',      path: [Array],      type: 'any.invalid',      context: [Object]    }  ]}


const Joi = require('@hapi/joi');Joi.object({    password: Joi        .string()        .custom((value, helper) => {            if (value.length < 8) {                return helper.message("Password must be at least 8 characters long")            } else {                return true            }        })}).validate({    password: '1234'});


This is how I validated my code, have a look at it and try to format yours

const busInput = (req) => {  const schema = Joi.object().keys({    routId: Joi.number().integer().required().min(1)      .max(150),    bus_plate: Joi.string().required().min(5),    currentLocation: Joi.string().required().custom((value, helper) => {      const coordinates = req.body.currentLocation.split(',');      const lat = coordinates[0].trim();      const long = coordinates[1].trim();      const valRegex = /-?\d/;      if (!valRegex.test(lat)) {        return helper.message('Laltitude must be numbers');      }      if (!valRegex.test(long)) {        return helper.message('Longitude must be numbers');      }    }),    bus_status: Joi.string().required().valid('active', 'inactive'),  });  return schema.validate(req.body);};