![](/img/trans.png)
[英]How to skip validation for last object in fieldArray form using yup validation schema with react-hook-form?
[英]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.