【问题标题】:How can i compare two times using joi library我如何使用 joi 库比较两次
【发布时间】:2021-01-01 01:36:24
【问题描述】:

我有两次字段。我需要使用 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});
}

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

【问题讨论】:

    标签: node.js joi


    【解决方案1】:

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

    您可以删除plantime,并提供一个custom validation function,实现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

    【讨论】:

    • 感谢您的回复并提供解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2023-03-20
    相关资源
    最近更新 更多