How to validate an Object with optional properties ? #713
-
What do we have ?Let's take this simple example type Data = {
email?: string | undefined;
password?: string | undefined;
} What is expected ?I want to validate my data to be sure it is an object, and that each defined property is a string. What was done ?const Schema = v.partial(
v.object({
email: v.string(),
password: v.string(),
}),
); The IssueWhen I pass an array as data the test does not fail. const result = v.safeParse(Schema, []);
// RESULT
[log]: {
typed: true,
success: true,
output: {},
issues: undefined
} I don't know if I'm missing something or doing something wrong, but if anyone can enlighten me on this that would be great To test: Playground |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Any complex data structure extends from an object in JavaScript. This includes arrays. An array has all the properties of an object. Previously we had a strict check for plain objects, but this caused many problems in different environments. That's why we decided to only check for |
Beta Was this translation helpful? Give feedback.
-
Okay, I see, it's a pretty restrictive situation I must say. Even though I don't like this solution, I will use this workaround for now const Schema = v.pipe(
v.custom((input) => input.constructor.name === "Object", "Should be an object"),
v.partial(
v.object({
email: v.string(),
password: v.string(),
}),
),
); Important For anyone who will be using this workaround, you should be aware that the order of the schema is important, as it appears that it is not the original object that is passed as input via the schemas (to verify, because I am not very familiar with this library), therefore it will not work if the schema @fabian-hiller Thank you for your reply. your responsiveness is crazy. I appreciate 🙏 |
Beta Was this translation helpful? Give feedback.
I recommend using
input && typeof input === 'object' && input.constructor === Object
, since the name of a constructor can be easily manipulated. Here are related issues: #587, #602, #608.