0
votes

Got react project and get list of needed inputs from BE. Creating validating Schema object need to use or not fields depending on condition exist this field in object from BE or not. Got this solution but don't know is it ok?

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')},});
1

1 Answers

0
votes

I think this would work

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') }));
}

If the validations are actually all the same, then you could:

fieldsList.forEach((name) => {
  validationSchema.concat(yup.object({ [name]: yup.string().required('required') }));
})