【问题标题】:How to Joi-Allow an empty Date String [Joi]如何 Joi-允许空的日期字符串 [Joi]
【发布时间】:2020-09-29 10:11:21
【问题描述】:

如标题所述,如何通过 Joi 验证允许空的 Date-String。

添加时:

Date: ""

遇到问题message: ""Date" must be a number of milliseconds or valid date string"

使用此 Joi 验证:

"Date": Joi.date().required().allow("").allow(null).options(validationErrors);

问题:如何通过 Joi 验证允许空的 Date-String?

编辑:通过删除:.required() 和/或添加.default(""),当添加Date: ""Cannot set parameter at row: 1. Wrong input for DATE type 时,我确实遇到了另一个错误

【问题讨论】:

  • 移除.required() 并设置.default("") 这样如果用户没有指定任何内容,你就有一个输入,当用户指定一个有效的时间戳时
  • 我在 EDIT 中添加了新信息。
  • 没有“编辑”
  • 错了,再检查一遍!

标签: javascript date validation joi


【解决方案1】:

你可以简单地从上面的代码中删除required()

"Date": Joi.date().allow("").allow(null).options(validationErrors);

【讨论】:

    【解决方案2】:

    有效:new Date()""(空字符串)

    joi版本17.2.1

    const joi = require('joi');
    
    const schema = joi.object().keys({
      "Date": joi.alternatives([
        joi.date(),
        joi.string().valid('')
      ]).required()
    }).required();
    
    // success
    const value = {
      "Date": "",
    };
    
    // success
    const value = {
      "Date": new Date(),
    };
    
    // error
    const value = {
      "Date": null,
    };
    
    // error
    const value = {
    
    };
    
    // error
    const value = {
      "Date": "invalid string"
    };
    
    
    const report = schema.validate(value);
    console.log(report.error);
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2017-07-11
      • 2022-11-12
      • 2018-01-12
      • 2019-08-08
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多