是的验证模式对象条件验证

Yup validation schema object conditional validation

我想简单地说 if type = 1 then validate the membership object , did try it with .when() 但不得不用对象的 eacth 来做(只有当 type =1 then validate

 validationSchema={Yup.object().shape({
                        //General
                        name: Yup.string().min(3).required('Name is required.'),
                        email: Yup.string().email().required('Email is required.'),
                        contactNo: Yup.number().required('Number is required.'),
                        address: Yup.string().required('Address is required.'),
                        country: Yup.string().required('Country is required.'),
    
    
                        memberShip: Yup.object() 
                        .shape({
//Something like this
if(type ===1){
                            memberShipNo: Yup.string().required('MemberShip Number is required.'),
                            memberShipStart: Yup.string().required( 'MemberShip Number is required.'),
                            fee: Yup.string().required('MemberShip Number is required.')},
                        }),
                        
                     
    
                        verified: Yup.bool(),
                    })}

解决渲染条件字段问题的一种方法是使用三元和传播。此解决方案确实需要一点点重复代码,并且可能还有其他(更好的)方法,但如果您想要更好的解决方案,您可以继续研究。

在此示例中,如果 type === 1 则所有字段都是 required 否则不是必需的,但可选。

 memberShip: Yup.object()
  .shape({
    ...(type === 1 ? {
      memberShipNo: Yup.string().required('MemberShip Number is required.'),
      memberShipStart: Yup.string().required('MemberShip Number is required.'),
      fee: Yup.string().required('MemberShip Number is required.')
    } : {
      memberShipNo: Yup.string(),
      memberShipStart: Yup.string(),
      fee: Yup.string()
    }),
  }),