繁体   English   中英

使用和 react-hook-form 进行 React yup 验证,不同类型对象的数组取决于 object 属性之一

[英]React yup validation with and react-hook-form, array of different type of objects depends from one of object attribute

我有一个表格,用户可以无限制地添加(添加股东)。

股东可以是 2 种不同的类型(自然/法律)

这是 thouse 对象的接口:

export interface shareholderNatural {
  type: 'NATURAL';
  firstName: string;
  lastName: string;
  personalCode: string;
  sharePart: number;
  politicallyExposed: boolean;
  country: string;
  position: string;
}

export interface shareholderLegal {
  type: 'LEGAL';
  companyName: string;
  companyCode: string;
  sharePart: number;
  politicallyExposed: boolean;
  country: string;
  position: string;
}

我需要验证:firstName、lastName、personalCode、sharePart 如果类型是 NATURAL companyName、companyCode、sharePart 如果类型是 NATURAL

当用户单击 opn 添加另一个共享者按钮 (useState) 时,属性类型由组件 state 中的 select 设置

我试着用 Yup.array().when('key', {})

 const validationSchema = Yup.object().shape({
shareholders: Yup.array().when('type', {
  is: 'NATURAL',
  then: Yup.array().of(
    Yup.object().shape({
      firstName: Yup.string().required(t('')),
      lastName: Yup.string().required(t('')),
      personalCode: Yup.string().required(t('')),
      sharePart: Yup.number().required(t('')),
    }),
  ),
  otherwise: Yup.array().of(
    Yup.object().shape({
      companyName: Yup.string().required(t('')),
      companyCode: Yup.string().required(t('')),
      sharePart: Yup.number().required(t('')),
    }),
  ),
}),

});

但在这种情况下,关键属性应该在外面......

这里有什么帮助吗? 谢谢你。

您可以分别检查每个字段。 只需将type替换为所需字段:

 const validationSchema = Yup.object().shape({ shareholders: Yup.array().of( Yup.object().shape({ firstName: Yup.string().when('type', { is: 'NATURAL', then: Yup.string().required(t('')) }), lastName: Yup.string().when('type', { is: 'NATURAL', then: Yup.string().required(t('')) }), personalCode: Yup.string().when('type', { is: 'NATURAL', then: Yup.string().required(t('')) }), sharePart: Yup.number().required(t('')), companyName: Yup.string().when('type', { is: 'LEGAL', then: Yup.string().required(t('')) }), companyCode: Yup.string().when('type', { is: 'LEGAL', then: Yup.string().required(t('')) }), }) ) ) };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM