superstruct
superstruct copied to clipboard
How to make custom validator across object properties?
I need to validate that of two object properties, at least one is populated:
message.content.length || message.images.length
How do you do that using superstruct?
On a (potentially) separate note, it would be nice if, for arbitrarily custom cases, you could just pass a function which is expected to return true
. Something like:
assert(() => message.content.length || message.images.length);
If false
, throws. Maybe add a string to populate the error message.
one way to validate that would be:
assert(message.content.length ?? message.images.length, number())
// Uncaught StructError: Expected a number, but received: undefined
another one:
assert(message.content ?? message.images, object({ length: number() }))
// Uncaught StructError: At path: length -- Expected a number, but received: undefined
If you want to check if the length is greater than 0, then:
assert(message.content.length || message.images.length, min(number(), 1))
// Uncaught StructError: Expected a number greater than or equal to 1 but received `0`
Hello, I also need to validate that one of two fields are not undefined :
const MyStruct = object({
a: string(),
b: string(),
});
//should be ok
validate({a:'a'},MyStruct);
validate({b:'b'},MyStruct);
//should throw error
validate({},MyStruct);
How can I do that using superstruct please?