HomeToolsAbout a20k

Yup

What is it

Yup is a schema builder for runtime value parsing and validation

  • Define a schema, transform a value to match, assert the shape of an existing value, or both
  • Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformation

Using

Why use yup

Validate your business objects against a predefined schema

  • Since the schema can be defined independently, unit testing can be done easily

Can handle complex validation

  • e.g. "when the validation of field A depends on the state of other fields B"
// yup definition const personSchema = yup.object({ firstName: yup.string(), nickName: yup.string().nullable(), email: yup .string() .nullable() .notRequired() .email(), birthDate: yup .date() .nullable() .notRequired() .min(new Date(1900, 0, 1)) }); // data to test against validation const person = { firstName: "Matt", nickName: "The Hammer", email: "matt@the-hammer.com", birthDate: new Date(1976, 9, 5) }; // run validation personSchema.isValidSync(person); // true

When using Typescript, maintaining both the variable's type and schema type can be redundant.

Here is a workaround:

type Person = yup.InferType<typeof personSchema>; const person: Person;

yup.object()

const schema = object({ id: string().required(), names: object({ first: string().required(), }), }); schema.isValid({ id: 1 }); // false! names.first is required

yup.object.shape()

You can chain .shape() method, which acts like Object.assign()

object({ a: string(), b: number(), }).shape({ b: string(), c: number(), }); // same as object({ a: string(), b: string(), c: number(), });
© VincentVanKoh