2

I am using https://github.com/jquense/yup#yup

I want to have an object validation schema for:

subObjectField: {
    [thisKeyCanBeAnyString]: string | string[] // allow string or array of strings
}

I cannot find an example or a starting point to achieve this, any ideas?

Zac
  • 1,719
  • 3
  • 27
  • 48
  • Does this answer your question? [Yup validate is either String or Array of strings](https://stackoverflow.com/questions/56855869/yup-validate-is-either-string-or-array-of-strings) – user17255676 May 03 '22 at 23:35
  • For the value part, but how can I validate that this object `subObjectField` can have 'any keys' ? – Zac May 04 '22 at 15:41

2 Answers2

1

I've put together a function which makes this easy:

  export const objectOf = (schema) => ({
      name: 'objectOf',
      exclusive: false,
      message: "Object values don't match the given schema",
      test: value => {
        return value === null || Object.values(value).every(schema.isValidSync(value));
      }
    });

example:

yup.object().test(objectOf(yup.number())).nullable()

this successfully passes for null and for objects of numbers like { foo: 52, bar: -12 }

0

Building on Arnošt's answer (which should be marked correct). Here's a typescript version:

import type { AnySchema } from 'yup';

export const yupObjectOf = <T extends AnySchema>(schema: T) => ({
  name: 'objectOf',
  exclusive: false,
  message: "Object values don't match the given schema",
  test: (value: null | Record<string, unknown>) => {
    return value === null || Object.values(value)
      .every(() => schema.isValidSync(value));
  }
});

TheHiggsBroson
  • 1,410
  • 1
  • 11
  • 19