Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yup.js object validation, allow any key but values must be string or string array

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?

like image 208
Zac Avatar asked Sep 18 '25 19:09

Zac


1 Answers

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 }

like image 173
Arnošt Neurad Avatar answered Sep 20 '25 10:09

Arnošt Neurad