我如何使用 joi 库比较两次

How can i compare two times using joi library

我有两个时间字段。我需要使用 joi 库应用验证, 目前我已经应用了验证,它显示错误为: TypeError: joi.string(...).required(...).less 不是函数。 验证计划开始时间应小于计划结束时间。 ! 我完成了以下代码:

{
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});
}

我怎样才能实现这个验证。

您需要确保您使用的是正确的类型。 string 没有定义 less 方法,因此会出现错误。

您可以删除 plantime,并提供 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
});

另一个要考虑的选项是使用 date 类型(顺便说一句,你不需要知道日期吗,不仅仅是时间?):

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

如果您随后想以某种方式格式化 plannedstarttimeplannedendtime,请使用 format。该格式应适用于 moment.js formatting。例如,仅显示小时+分钟的格式为 HH:mm.