Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
How can I validate that req.body has a valid date string using Joi in node JS

I have made a validation middleware whose code is given below like this.

export const validateMiddleware = async (req, res, next) => {

    const validateExpression = Joi.object()
        .keys({
            'startDate': Joi.string()
                .optional()
                .allow(''),
             'endDate': Joi.string()
                 .optional()
                 .allow('')
        });

    const {
        error
    } = validateExpression.validate(req.query, {
        'convert': false,
        'abortEarly': false
    });

    if (error) {
       // Return response regarding that error.
    } else {
        next();
    }
};

I need to validate that startDate and endDate fields should be string of format YYYY-MM-DD also need to validate that startDate < endDate date value. How can I achieve this using Joi in Node JS ?.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think this code will solve your problem:

const validateExpression = Joi.object()
  .keys({
    'startDate': Joi.date()
      .format("YYYY-MM-DD")
      .optional()
      .allow(''),
    'endDate': Joi.date()
      .format("YYYY-MM-DD")
      .optional()
      .allow('')
      .min(Joi.ref('startDate'))
  });
about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this:


const Joi = require("joi").extend(require("@joi/date"));


export const validateMiddleware = async (req, res, next) => {

    const validateExpression = Joi.object()
        .keys({
            'startDate': Joi.date()
                .format("YYYY-MM-DD")
                .strict(false) // required if 'convert' option is set to "false"
                .optional()
                .allow(''),
             'endDate': Joi.date()
                .format("YYYY-MM-DD")
                .greater(Joi.ref("startDate")) // checks if it is greater than startDate, throws error if now.
                .strict(false) // can be omitted if 'convert' option is set to "true"
                .optional()
                .allow('')
        });

    const {
        error
    } = validateExpression.validate(req.query, {
        'convert': false,
        'abortEarly': false
    });

    if (error) {
       // Return response regarding that error.
    } else {
        next();
    }
};

DO NOT forget to call strict(false). Otherwise passing date as string won't work, since you have 'convert': false. Or alternatively, you can set 'convert': true (which is the default value anyway) and you won't need to call string(false) on startDate and endDate.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda