Yup Date Format Validation With Moment JS

Using the combination of yup and moment js, here’s how we can validate the format and correctness of the date:

const { string } = require("yup");
const moment = require("moment");

const dateSchema = string().test(
  "date validation",
  "Invalid date or format. The string should be a valid YYYY-MM-DD format.",
  val => {
    if (!val) {
      return true;
    }
    return moment(val, "YYYY-MM-DD", true).isValid();
  }
);

We use string() validation and add a test() step with our custom type and error messages.

In the function, we ensure that the value exists and that it’s a valid date and in a valid format.

Examples

try {
  console.log(dateSchema.validateSync("2023"));
} catch (e) {
  console.log(e.errors);
}

try {
  console.log(dateSchema.validateSync("7-7-2023"));
} catch (e) {
  console.log(e.errors);
}

try {
  console.log(dateSchema.validateSync("7-2023"));
} catch (e) {
  console.log(e.errors);
}

try {
  console.log(dateSchema.validateSync("2023-02-29"));
} catch (e) {
  console.log(e.errors);
}

try {
  console.log(dateSchema.validateSync("2024-02-29"));
} catch (e) {
  console.log(e.errors);
}

try {
  console.log(dateSchema.validateSync("2023-07-07"));
} catch (e) {
  console.log(e.errors);
}

The above calls will result in:

[
  'Invalid date or format. The string should be a valid YYYY-MM-DD format.'
]
[
  'Invalid date or format. The string should be a valid YYYY-MM-DD format.'
]
[
  'Invalid date or format. The string should be a valid YYYY-MM-DD format.'
]
[
  'Invalid date or format. The string should be a valid YYYY-MM-DD format.'
]
2024-02-29
2023-07-07

Notice that 2023-02-29, although the correct format, is not a valid date because 2023 is not a leap year, whereas 2024-02-29 is.




See also

When you purchase through links on techighness.com, I may earn an affiliate commission.