Hi,
I'm trying to combine several schemas into 1 and the documentation mentioned that only 2 schemas can be combined using "concat"
I have kind of achieved it by chaining "concat" after one another but I'm wondering if there's a more elegant of achieving it.
Here is the example:
import * as Yup from 'yup'
const isRequired = 1
const isMin = 1
/* Default */
const stringSchema = Yup.string()
const policySchema = Yup.string().matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])/)
/* Optional */
const isRequiredSchema = Yup.string().required()
const minSchema = Yup.string().min(9)
/* Concat */
const defaultPasswordSchema = stringSchema.concat(policySchema)
const hasRequired = defaultPasswordSchema.concat(
isRequired === 1 ? isRequiredSchema : null)
const PasswordSchema = hasRequired.concat(
isMin === 1 ? minSchema : null)
export default PasswordSchema
Apparently .concat can be chained. I managed to join multiple schemas as shown by the example below:
import * as Yup from 'yup';
const isNumber= Yup.number();
const isRequiredNumber = Yup.number().required();
const noZero = Yup.number().min(1);
const userRoleSchema= isNumber.concat(isRequiredNumber).concat(noZero);
export default userRoleSchema
A generic implementation could like this:
function merge(...schemas) {
const [first, ...rest] = schemas;
const merged = rest.reduce(
(mergedSchemas, schema) => mergedSchemas.concat(schema),
first
);
return merged;
}
// usage:
const merged = merge(schema1, schema2, schema3, etc);
Another implementation could look like this:
const schema1 = object({
a: string(),
b: array(),
});
const schema2 = schema1.shape({
b: object(),
});
schema2 will be:
const schema2 = object({
a: string(),
b: object(),
});
Most helpful comment
Another implementation could look like this:
schema2will be: