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
- SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
- Yup Number Validation: Allow Empty String
- Exactly Same Query Behaving Differently in Mongo Client and Mongoose
- JavaScript Unit Testing JSON Schema Validation
- Reduce JS Size With Constant Strings
- JavaScript SDK
- JavaScript: Find if the String Has a Particular Case