获得react项目并从BE获得所需输入的列表。创建验证模式对象需要使用或不使用字段,这取决于对象中是否存在此字段。得到了这个解决方案,但不知道它是否可以?
const validationSchema = yup.object().shape({
...('phone' in fieldsList) && {'phone': yup.string().required('required')},
...('password' in fieldsList) && {'password': yup.string().required('required')},
...('email' in fieldsList) && {'email': yup.string().required('required')},
...('name' in fieldsList) && {'name': yup.string().required('required')},});
我想这可以。
const validationSchema = yup.object();
if ('phone' in fieldsList) {
validationSchema.concat(yup.object({ 'phone': yup.string().required('required') }));
}
if ('password' in fieldsList) {
validationSchema.concat(yup.object({ 'password': yup.string().required('required') }));
}
if ('email' in fieldsList) {
validationSchema.concat(yup.object({ 'email': yup.string().required('required') }));
}
if ('email' in fieldsList) {
validationSchema.concat(yup.object({ 'email': yup.string().required('required') }));
}
如果验证实际上都是相同的,那么您可以:
fieldsList.forEach((name) => {
validationSchema.concat(yup.object({ [name]: yup.string().required('required') }));
})