Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
Is there a way to use callback functions in joi validation?

Their Guru's

I'm doin a research on a code I saw on the internet, but if I see the syntax, they have used Hapi/Joi which is depricated. My question is how can I use this syntax in Joi?

app.post('/test', (req, res, next) => {

const id = Math.ceil(Math.random() * 9999999);

  Joi.validate(data, schema, (err, value) => {


    if (err) {
      res.status(400).json({
        status: 'error',
        message: 'Invalid request data',
        data: data
      });
    } else {
      res.status(200).json({
        status: 'success',
        message: 'User created successfully',
        data: Object.assign({id}, value)
      });
    }
  });
});

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

By inspecting the types (index.ds.ts) file in Github indeed there is no callback style validate function, only those two methods:

        /**
         * Validates a value using the schema and options.
         */
        validate(value: any, options?: ValidationOptions): ValidationResult;

        /**
         * Validates a value using the schema and options.
         */
        validateAsync(value: any, options?: AsyncValidationOptions): Promise<any>;

However you can use util.callbackify - callbackify examples to transform validateAsync into a callback node style if you really want to:

const Joi = require('joi');
const { callbackify } = require('util');

// A very simple data object
const obj = { a: 23 };

// A very simple joi schema which checks if schema is an object with the `a` property being a string
const schema = Joi.object({
  a: Joi.string(),
});

// Callback style (which i don't recommend since its not available in `joi` package)
callbackify(() => schema.validateAsync(obj))((err, ret) => {
  if (err) {
    return res.status(400).json({
      status: 'error',
      message: 'Invalid request data',
      data: data,
    });
  }
  res.status(200).json({
    status: 'success',
    message: 'User created successfully',
    data: Object.assign({ id }, value),
  });
});

I would use what Joi provide, as in the following 2 examples:

// using async/await - you need to mark you controller as async, like:
// app.post('/test', async (req, res, next) => ...

try {
  await schema.validateAsync(obj);
  res.status(200).json({
    status: 'success',
    message: 'User created successfully',
    data: Object.assign({ id }, value),
  });
} catch (err) {
  res.status(400).json({
    status: 'error',
    message: 'Invalid request data',
    data: data,
  });
}

Or even with just promises:

schema
  .validateAsync(obj)
  .then(() =>
    res.status(200).json({
      status: 'success',
      message: 'User created successfully',
      data: Object.assign({ id }, value),
    })
  )
  .catch(() =>
    res.status(400).json({
      status: 'error',
      message: 'Invalid request data',
      data: data,
    })
  );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!