Yup
is a schema builder for runtime value parsing and validation
Using
yup
Validate your business objects against a predefined schema
Can handle complex validation
// 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(), });