[英]React yup validation with and react-hook-form, array of different type of objects depends from one of object attribute
I have a form, where user can add with no limit ( add shareholder ).我有一个表格,用户可以无限制地添加(添加股东)。
Shareholder can be 2 different types ( NATURAL / LEGAL )股东可以是 2 种不同的类型(自然/法律)
here is interface for thouse objects:这是 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;
}
I need validation for: firstName, lastName, personalCode, sharePart if type is NATURAL companyName, companyCode, sharePart if type is NATURAL我需要验证:firstName、lastName、personalCode、sharePart 如果类型是 NATURAL companyName、companyCode、sharePart 如果类型是 NATURAL
Attribut type is set by the select from the component state when user click opn add another sharehoilder button (useState)当用户单击 opn 添加另一个共享者按钮 (useState) 时,属性类型由组件 state 中的 select 设置
I tryed to do it with Yup.array().when( 'key', {})我试着用 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('')),
}),
),
}),
}); });
But in this case key attribute should be outside...但在这种情况下,关键属性应该在外面......
Any help here?这里有什么帮助吗? Thank you.
谢谢你。
You can check every field separately.您可以分别检查每个字段。 Just replace
type
with needed field:只需将
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.