superstruct icon indicating copy to clipboard operation
superstruct copied to clipboard

How to make custom validator across object properties?

Open dchacke opened this issue 2 years ago • 2 comments

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.

dchacke avatar Mar 08 '22 23:03 dchacke

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`

micalevisk avatar May 15 '22 23:05 micalevisk

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?

Ayora29 avatar Jul 18 '22 08:07 Ayora29