【问题标题】:How to format JOI date/schema correctly?如何正确格式化 JOI 日期/模式?
【发布时间】:2020-01-07 14:07:10
【问题描述】:

我有一个通过obj.pattern 强制验证限制的函数。 我要验证的关键是格式化的日期,它以以下格式提供给函数DD/MM/YYYY

我正在使用Joi.date 来验证这个值,当日期小于每月 12 日时,这很好。如果更多,则返回错误。假设默认 JOI 格式为MM/DD/YYYY,这显然会导致错误,因为日历年有 12 个月。 这反映在控制台日志中 - 如果我将 numberField 中的日期值更改为大于 12 的任何值,那么我可以看到错误。如果它保持在以下,则不会引发错误。

我想弄清楚如何格式化此响应,以便 JOI 可以验证正确的架构。我已将问题简化并简化为我在此分享的原型:https://codesandbox.io/embed/naughty-booth-862wb

谁能帮忙?

【问题讨论】:

    标签: javascript joi


    【解决方案1】:

    您需要利用joi-date 包中的.format() 方法来设置自定义日期格式。请参阅内联 cmets。

        import "./styles.css";
        import JoiBase from "@hapi/joi";
        import JoiDate from "@hapi/joi-date";
    
        const Joi = JoiBase.extend(JoiDate); // extend Joi with Joi Date
    
        document.getElementById("app").innerHTML = `
        <h1>Hello Vanilla!</h1>
        <div>
          We use Parcel to bundle this sandbox, you can find more info about Parcel
          <a href="https://parceljs.org" target="_blank" rel="noopener noreferrer">here</a>.
        </div>
        `;
        export const dateRequired = (keys, message) => {
          return Joi.object().pattern(
            Joi.valid(keys),
            Joi.date()
              .format("DD/MM/YYYY") // set desired date format here
              .raw()
              .error(() => "message")
          );
        };
    
        const state = {
          numberField: "14/09/1995" // "14/9/1995" will fail without leading "0" on 09
        };
        const schema = dateRequired(["numberField"]);
    
        const valid = Joi.validate(state, schema); // "valid" is a promise
        valid
          .then(res => {
            console.log("SUCCESS", res);
          })
          .catch(e => {
            console.log("ERROR", e.toString());
          });
    

    https://codesandbox.io/embed/prod-grass-f95sz

    【讨论】:

    • 像魅力一样工作!谢谢:-)
    猜你喜欢
    • 2012-02-15
    • 2013-09-18
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多