Yup: Validate only some fields against schema

Created on 26 Feb 2019  路  3Comments  路  Source: jquense/yup

Given an schema:

export const companySchema = yup.object().shape({
  name: yup.string().required(),
  url: yup.string().required(),
  enabled: yup.boolean()
})

Is there a way to validate a set of values against this schema? For example if a form sends only the updated values

const updatedValues = {
  name: "Some new name"
}

Could I just validate the fields from the updatedValues object to check if the definition matches the schema name field without sending the errors from required fields?

companySchema.validate(updatedValues)

Edit:

Found a solution

Most helpful comment

would be simpler to do:

export const validateFields = async (data) => {
  for (const field of Object.keys(data)) {
    await companySchema.validateAt(key, data, { strict: true })

  }
}

(I forgot about validateAt)

All 3 comments

You can use reach to pull sections of the schema and individual validate those. There isn't a built in way tho to arbitrarily select a subset of a schema and validate that

Found a way around this in case someone else need it

const schemaValidations = {
  name: yup.string().required(),
  url: yup.string().required(),
  enabled: yup.boolean()
}
export const companySchema = {
  shape: yup.object().shape({
    ...schemaValidations
  }),
  ...schemaValidations
}

Then I created the method to validate the fields :

export const validateFields = async (data) => {
  for (const field of Object.keys(data)) {
    const schemaForField = companySchema[field]
    await schemaForField.validate(data[field], { strict: true }).catch(err => {
      // Handle errors
    })
  }
} 

```javascript
await validateFields(data)

would be simpler to do:

export const validateFields = async (data) => {
  for (const field of Object.keys(data)) {
    await companySchema.validateAt(key, data, { strict: true })

  }
}

(I forgot about validateAt)

Was this page helpful?
0 / 5 - 0 ratings