0
votes

I'm trying to use Yup to validate data in an array. For example, this is my initialValue:

{name:'',extra:[]}

After dynamic render the form field , the initialValue will become like this:

{name:'',extra:[{label:'age',value:'',required:true}]}

I want to set the validation scheme to validate the 'value' in the object only when 'required' is true.

I use this data to mock the situation:

{name:'john',extra:[{label:'age',value:'',required:true}]};

Method that i had try:

const validationschema = yup.object().shape({
 name: yup.string().required(),
  extra: yup.lazy((value,index)=>{
    return yup.mixed().required();
  })
})

There should be an error when the user submit , because the 'value' for age is empty. I not sure why, i can't really validate the 'value'. How do I change my validationschema so it can validate the 'value' ?

1

1 Answers

0
votes

Try to validate like:

name: yup.string().required(),
extra: yup.array()
  .of(
   yup.object().shape({
     required: yup.bool(),
     value: yup.object().when('required', {
       is: true,
       then: yup.string().required('Please, select position')
     }),
   })
  )

There you should check field required. If it true you validate it.