Extending one key on a Yup schema

Viewed 4319

I'm creating some Yup schemas, for example:

    let validationSchema = yup.object({
      length: yup.number().min(1)
    });

Is there a way to extend this after it has been declared so it's like I set the schema like this?

    let validationSchema = yup.object({
      length: yup.number().min(1).required(true)
    });
1 Answers

The closest thing to schema extension/inheritance in Yup is to use object.shape to create a new schema based on existing schema: Yup documentation

object.shape(fields: object, noSortEdges?: Array<[string, string]>): Schema

Define the keys of the object and the schemas for said keys. Note that you can chain shape method, which acts like object extends

const baseSchema = Yup.object().shape({
   id: string().isRequired(),  
  name: string().isRequired()
})

const someSchema = baseSchema.shape({
   id: number().isRequired(),
   age: number().isRequired()
})

which is equivalent to:

const someSchema = Yup.object().shape({
   id: number().isRequired(), // notice how 'id' is overridden by child schema
   name: string().isRequired(),
   age: number().isRequired()
})

Another way is to use concat(schema) to create a new schema instance by combing two schemas: Yup documentation

mixed.concat(schema: Schema): Schema Creates a new instance of the schema by combining two schemas. Only schemas of the same type can be concatenated.

const baseSchema = Yup.object().shape({
   name: string().isRequired()
})

const someSchema = baseSchema.concat(
   Yup.object().shape({
    age: number().isRequired()
}))

// someSchema will be equipped with both `name` and `age` attributes 

Please note that concat only works when two schema objects have different properties or same properties with exact same type.

Related