0

I have two times fields. I need to apply validation using joi library, Currently i have applied a validation it is showing error as : TypeError: joi.string(...).required(...).less is not a function. The validation is Planned Start time should be less than Planned End time. ! I have done the following code:

{
schema=joi.object({
  taskname:joi.string().required().label('Please enter Task Description!'),
  task:joi.string().invalid(' ').required().label('Please enter Task Description!'),
  taskn:joi.string().min(1).max(80).required().label(' Task Description too long.'),
  projectname:joi.string().required().label('Please select Project !'),
  type:joi.string().required().label('Please select Task Type !'),
  status:joi.string().invalid('None').required().label('Please choose Status'),
  plannedstarttime:joi.string().regex(/^([0-9]{2})\:([0-9]{2})$/).required().label('Please fill Planned Start Time !'),
  plannedendtime:joi.string().regex(/^([0-9]{2})\:([0-9]{2})$/).required().label('Please fill Planned 
   End Time !'),
  plantime:joi.string().required().less(joi.ref('plannedendtime')).label('Planned Start time should 
  be less than Planned End time. !'),
}) 
result=schema.validate({taskname:taskname,task:taskname,taskn:taskname,type:tasktype,projectname:projectname,status:request.body.status,plannedstarttime:plannedstarttime,plannedendtime:plannedendtime,plantime:plannedstarttime});
}

How can i achieve this validation.

OfirD
  • 9,442
  • 5
  • 47
  • 90

1 Answers1

0

You need to make sure you're working with the correct types. string doesn't define a less method, thus you get an error.

You can remove plantime, and provide a custom validation function, that implements a string comparison:

schema = joi.object({
  ...
  // plantime: // <-- remove it
  ...
}).custom((doc, helpers) => {
    if (doc.plannedstarttime > doc.plannedendtime) {
        throw new Error("Planned Start time should be lower than Planned End time!");
    }
    return doc; // Return the value unchanged
});

Another option to consider is to work with a date type (BTW, don't you need to know the date as well, no just time?):

schema = joi.object({
  ...
  plannedstarttime: joi.date().required() ...
  plannedendtime: joi.date().required().greater(joi.ref('plannedstarttime')) ...
  // plantime // <-- remove it
  ...
});

If you then want to format plannedstarttime and plannedendtime in a certain way, use format. The format should apply to moment.js formatting. For example, formatting to only show hour+minute is HH:mm.

OfirD
  • 9,442
  • 5
  • 47
  • 90