silva_edilson22
silva_edilson22

Reputation: 45

How could I validate dates correctly?

I'm using celebrate to validate dates but I can still add a start_date higher than the end_date, what could I do to prevent this behaviour? Also using the format like this returns the following error:

Unknown date format YYYY-MM-DD

What can I do to use the desired format?

routes.post(
  '/world_series',
  celebrate({
    [Segments.BODY]: Joi.object().keys({
      start_date: Joi.date().required(),
      end_date: Joi.date().format('YYYY-MM-DD').greater(Joi.ref('start_date')).required(),
      champion_id: Joi.string().required(),
      runners_up_id: Joi.string().required(),
    }),
  }),
  WorldSeriesController.create
);

Upvotes: 0

Views: 3142

Answers (1)

silva_edilson22
silva_edilson22

Reputation: 45

After reading the documentation I saw that I could use the ruleset to solve my problem, here's the code:

routes.post(
  '/world_series',
  celebrate({
    [Segments.BODY]: Joi.object().keys({
      start_date: Joi.date().required(),
      end_date: Joi.date()
        .ruleset.greater(Joi.ref('start_date'))
        .rule({ message: 'end_date must be greater than start_date' })
        .required(),
      champion_id: Joi.string().required(),
      runners_up_id: Joi.string().required(),
    }),
  }),
  WorldSeriesController.create
);

Upvotes: 2

Related Questions