jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

Yup validation for empty object #2107

Open viet34tqc opened 1 year ago

viet34tqc commented 1 year ago

Hi, I'm trying to create a Yup schema to validate an object and this object must not be empty object ({}). The problem I'm having is the keys of the object are dynamic and not available ahead of time.

Here is my first try:

const validationShema = yup.object().shape({
  mainCondition: yup.lazy((value) => {
    if (!value) {
      const shapeOfKey = Object.keys(value).reduce(
        (acc, val) => ({
          ...acc,
          [val]: yup.string(),
        }),
        {},
      )
      return yup.object().shape(shapeOfKey)
    }
    return yup.object().required('Main Condition is required')
  }),
})

The name of the key is not necessary. I just need the mainCondition not to be an empty object. Is this possible to achieve?

Thanks