是的,基于嵌套对象内的嵌套对象进行验证

Rob*_*ell 2 javascript reactjs yup formik

我目前有一个如下所示的对象:

const initialValues = {
  created: {
    position: 1,
    name: 'created',
    type: 'timestamp',
    desc: 'The date and time the lead is created',
    mapping: {
      name: '',
      defaultValue: '',
      map: false
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望当映射对象中的映射值设置为 true 时,映射对象中的名称成为必需的。我已尝试通过执行以下操作:

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')
      })
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

我相信我没有足够的隧道来准确设置映射对象的验证,任何和所有帮助/建议将不胜感激。

Rob*_*ell 5

我发现解决方案执行以下操作:

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')
      })
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢——你帮我解决了很多头痛问题 (3认同)