as the title states, how to allow an empty Date-String through Joi validation.
When adding:
JavaScript
x
2
1
Date: ""
2
it gets the Issue: message: ""Date" must be a number of milliseconds or valid date string"
with this Joi-Validation:
JavaScript
1
2
1
"Date": Joi.date().required().allow("").allow(null).options(validationErrors);
2
Question: How can an empty Date-String be allowed through Joi validation?
EDIT: By removing: .required()
and or adding .default("")
i do get another error, when adding Date: ""
, Cannot set parameter at row: 1. Wrong input for DATE type
Advertisement
Answer
Valid: Either new Date()
or ""
(empty string)
joi
version 17.2.1
JavaScript
1
38
38
1
const joi = require('joi');
2
3
const schema = joi.object().keys({
4
"Date": joi.alternatives([
5
joi.date(),
6
joi.string().valid('')
7
]).required()
8
}).required();
9
10
// success
11
const value = {
12
"Date": "",
13
};
14
15
// success
16
const value = {
17
"Date": new Date(),
18
};
19
20
// error
21
const value = {
22
"Date": null,
23
};
24
25
// error
26
const value = {
27
28
};
29
30
// error
31
const value = {
32
"Date": "invalid string"
33
};
34
35
36
const report = schema.validate(value);
37
console.log(report.error);
38