'Yup schemas from React sub-components with namespace
EDIT: I pulled a backup from Git, and the schema seems to be the same as before my changes. However, when I go to use this form, the Yup validation is not being triggered. The form will take input, validate that the sub-form is required, but when you add an entry to the sub-form, Yup does not validate the sub-form, only the parent form. Does anyone know why the sub-form validation does not get triggered?
I am using Yup to verify Formik form input in React. I have a situation where I need to use a variable as part of the object keys in a sub-component. The sub-component can be used up to 5 times, and a namespace is used to identify the particular sub-component within the parent.
My normal way to resolve this would be to use bracket notation instead of dot notation/standard JSON format for the object, but Yup schemas are immutable. It looks like Yup is written in TypeScript which I'm not as familiar with.
The Yup schema in the sub-component(s) are being imported and concatenated into the schema in the parent component, and I'm not sure how to handle the variable namespace for the schema keys in the sub-component. I saw something in my research that looked like this:
Yup.object({
[`${variable}-name`]: Yup.string().max(....),
[`${variable}-amount`]: Yup.number().max(....)
});
But when hovering over the object, intellisense shows that the keys are in an array, which is not what I want. I simply want the variable value as part of the name of the key. Is this some TypeScript notation that I'm misunderstanding?
The function that combines the schemas:
//parent component
getValidationSchemaCombined(num) {
let validation = this.getValidationSchemaTopLevel(num);
if (num > 0) {
return validation.concat(
ExpandableForm.GetValidationSchema(num)
);
} else {
return validation;
}
}
//expandableform class
static GetValidationSchema(length) {
if (length === 0) {
return {};
}
let validationSchema = ExpandableForm.GetConvertedValidationSchema(0);
for (let i = 1; i < length; i++) {
let objVal = ExpandableForm.GetConvertedValidationSchema(i);
validationSchema = validationSchema.concat(objVal);
}
return validationSchema;
}
static GetConvertedValidationSchema(i) {
const val = SubForm.GetValidationSchema(
ExpandableForm.GetNamespace(i)
);
let objVal = Yup.object({ [ExpandableForm.GetNamespace(i)]: val });
return objVal;
}
//subform class
static GetValidationSchema(namespace) {
return Yup.object({
// this is the part where I need the variable in the key name and I'm not sure how to do it
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
