Yup: How do I validate an Object's properties against a defined shape?

Created on 12 Apr 2017  路  2Comments  路  Source: jquense/yup

Say I have an object I'm trying to validate that's a hash:

const myObj = {
  'abc': {
    name: 'John Doe'
  },
  'def': {
    name: 'Jane Doe'
  }
}

How would I go about validating this? Could I do something that checks the rules of the naming of the hashed properties, and then the shape of the object referenced?

const schema = yup.object({
  [yup.string().required]: yup.object({
    name: yup.string().required()
  })
})

Most helpful comment

a custom .test() on the object is what y'all want.

All 2 comments

The way I'm doing it is creating a schema with yup.object().shape(...)
Example object schema:

const schemaShape = {
     thing1: yup.string().required()
     thing2: yup.number().required().min(2).max(10)
}
const schema = yup.obect().shape(schemaShape)
testData = {
     thing1: "Dataaa",
     thing2: 8
}

schema.validate(testData).then.....

I'm pretty new to yup, but this is what I'm doing and it works for me.
@jtulk

a custom .test() on the object is what y'all want.

Was this page helpful?
0 / 5 - 0 ratings