最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Yup validation based on nested object within nested object - Stack Overflow

programmeradmin5浏览0评论

I currently have an object that looks like the following:

const initialValues = {
  created: {
    position: 1,
    name: 'created',
    type: 'timestamp',
    desc: 'The date and time the lead is created',
    mapping: {
      name: '',
      defaultValue: '',
      map: false
    }
  }
}

I would like the name within the mapping object to bee required when the map value within the map object is set to a value of true. I have attempted this by doing the following:

const validationSchema = yup.object({
  created: yup.object().when('mapping.map', {
    is: true,
    then: yup.object({
      mapping: yup.object({
        name: yup.string().required('name is required')
      })
    })
  })
})

I believe I'm not tunneling enough in order to accurately set up the validation for the mapping object, any and all help/suggestions would be greatly appreciated.

I currently have an object that looks like the following:

const initialValues = {
  created: {
    position: 1,
    name: 'created',
    type: 'timestamp',
    desc: 'The date and time the lead is created',
    mapping: {
      name: '',
      defaultValue: '',
      map: false
    }
  }
}

I would like the name within the mapping object to bee required when the map value within the map object is set to a value of true. I have attempted this by doing the following:

const validationSchema = yup.object({
  created: yup.object().when('mapping.map', {
    is: true,
    then: yup.object({
      mapping: yup.object({
        name: yup.string().required('name is required')
      })
    })
  })
})

I believe I'm not tunneling enough in order to accurately set up the validation for the mapping object, any and all help/suggestions would be greatly appreciated.

Share Improve this question edited Jun 2, 2022 at 16:14 Rob Terrell asked Jun 2, 2022 at 15:15 Rob TerrellRob Terrell 2,5624 gold badges21 silver badges47 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

I found the solution doing the following:

const validationSchema = yup.object({
  created: yup.object().shape({
    mapping: yup.object().shape({
      map: yup.boolean(),
      defaultValue: yup.string(),
      name: yup.string().when('map', {
        is: true,
        then: yup.string().required('name is required')
      })
    })
  })
})
发布评论

评论列表(0)

  1. 暂无评论