Can an array(union()) schema filter out invalid elements, rather than fail? #493
-
I don't know if this is an option within valibot or if we simply need to do this sort of data transformation before we hand the data to valibot to parse. Is there any way to allow an array(union([])) to kick invalid array entries from the output array rather than fail to parse. For example: const blockOneSchema = object({
type: literal("blockOne"),
id: string(),
color: picklist(["blue", "red"])
});
const blockTwoSchema = object({
type: literal("blockTwo"),
id: string(),
text: string()
});
const entrySchema = object({
name: string(),
blocks: array(union([blockOneSchema, blockTwoSchema]))
});
const exampleData = {
name: "entry",
blocks: [{
type: "blockOne",
id: "1",
color: "blue"
}, {
type: "blockTwo",
id: "2",
text: "stringValue"
}, {
type: "blockThree",
id: "3",
value: "This isn't in the union, oh no"
}]
}
const outputData = parse(entrySchema, exampleData); Basically I want the output to include the first two blocks, since they are valid according to our schema, and instead of failing to parse once it hits the third block — which isn't valid — it would simply remove it from the output array and give us all the valid blocks without a parse failure: {
name: "entry",
blocks: [{
type: "blockOne",
id: "1",
color: "blue"
}, {
type: "blockTwo",
id: "2",
text: "stringValue"
}
} Apologies if this is super wordy, but I'd appreciate any insight about how we can accomplish this. Just a note, I don't believe I can use variant() instead of union() in our actual code, because the literal we're using to differentiate each type is nested a few levels deep, and it doesn't look like there's any way to target a deeply nested discriminator key. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Try targeting the root key that contains the nested key. This should work.
Currently this functionality is not supported by default. Since Valibot follows a modular architecture, it can be easily extended with custom code. If you want, I can provide the code for a |
Beta Was this translation helpful? Give feedback.
Try targeting the root key that contains the nested key. This should work.
Currently this functionality is not supported by default. Since Valibot follows a modular architecture, it can be easily extended with custom code. If you want, I can provide the code for a
filterArray
function that does exactly what you want. If more users are interested in this…