javascriptjoi

How to format JOI date/schema correctly?


I've got a function which enforces validation restrictions via obj.pattern. The key which I would like to validate is a formatted date which is provided to the function in the following format DD/MM/YYYY.

I am using Joi.date to validate against this value which is fine when the day is less than the 12th of month. If it is more, it returns an error. The assumption is that the default JOI format is MM/DD/YYYY which would obviously result in an error since there are 12 months in the calendar year. This is reflected in the console log - If i change the day value in numberField to anything greater than 12 then I can see the error. If it stays below then there is no error thrown.

I would like to figure out how I can format this response so that JOI can validate the correct schema. I've simplified and reduced the issue to a prototype which I am sharing here: https://codesandbox.io/embed/naughty-booth-862wb

Can anyone help?


Solution

  • You need to utilize the .format() method in the joi-date package to set custom date formats. Please see the inline comments.

        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