Yup: Combining multiple schemas

Created on 8 Jun 2018  路  3Comments  路  Source: jquense/yup

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

Most helpful comment

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

All 3 comments

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(),
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ceilat picture ceilat  路  3Comments

AmineIT picture AmineIT  路  3Comments

the-daniel-rothig picture the-daniel-rothig  路  4Comments

aprat84 picture aprat84  路  4Comments

ScreamZ picture ScreamZ  路  4Comments