Replies: 2 comments
-
I don't think there is a straightforward way to do this, but you could do this at runtime by using |
Beta Was this translation helpful? Give feedback.
0 replies
-
If anyone wondering, here is my attempt at doing it: import { ZodObject, ZodRawShape } from 'zod'
import { ZodIssueCode } from 'zod/lib/ZodError'
function validateFilter<T extends ZodRawShape>(
schema: ZodObject<T>,
data: object,
): boolean {
console.log(`Passed data: ${JSON.stringify(data, null, 2)}`)
const result = schema.safeParse(data)
if (result.success) {
return true
} else {
for (const issue of result.error.issues) {
if (issue.code === ZodIssueCode.unrecognized_keys) {
for (const key of issue.keys) {
delete data[key]
}
}
}
const newResult = schema.safeParse(data)
if (newResult.success) {
return true
} else {
console.error(
'Failed to parse data after filtering invalid fields:',
newResult.error,
)
return false
}
}
}
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi, I have an object that's coming from outside that I need to put into in some guaranteed form, but NOT throw.
Basically, I want to make sure that the object's property matches the validation OR it's not included in the first place.
For a simple example, let's consider an object with a string field
foo
:However, this doesn't work because if
foo
is not a URL, it will throw instead of just dropping the property.Here's how it would ideally go:
Even transformers don't work, because I don't want the
foo
field with an undefined value to be in the object. I just want the key to not even be present in the first place.So far the only thing that seems like it could work is if I were to create a union of objects (not the
foo
field) in which thefoo
field is present and meets validation, or isn't present at all:However, I have 5 other properties like
foo
, and that means I'd need a union of 2^5 = 32 schemas, which is just untenable, especially as the number of properties may go up in the future.Is there any good way to do this other than a MASSIVE union of schemas, i.e. to do this at the field level so that
foo
either is accepted or is dropped (without throwing)?Thanks.
Beta Was this translation helpful? Give feedback.
All reactions