Yup Object Validation: The Complete Guide


Ensuring your objects follow the correct structure is essential for building reliable forms, APIs, and applications. Yup simplifies this process, letting you define, validate, and handle errors for objects in JavaScript.

Want to master object validation and reduce runtime errors in your apps? Read on to explore practical Yup object schemas and common validation scenarios.

Defining an Object Schema with Yup

When working with forms or API inputs, you often need to ensure the data has a specific structure. For example, let’s say we expect a user object with a name and age.

import * as yup from "yup";

// Define the schema for a user object
const userSchema = yup.object({
  name: yup.string().required("Name is required"),
  age: yup.number().required("Age is required").positive().integer(),
});

Explanation:

  • yup.object({...}) → creates a schema for an object.
  • Inside it, each key matches a property of the object.
  • name must be a string and is required.
  • age must be a positive integer (e.g., 25).

This defines the rules, but it doesn’t run validation yet.

Validating an Object Against the Yup Schema

Once you have a schema, you can validate data objects using .validate().

// Example data to validate
const userData = {
  name: "Sharukhan",
  age: 25,
};

// Validate the data
userSchema
  .validate(userData)
  .then((validData) => {
    console.log("Validation Passed:", validData);
  })
  .catch((error) => {
    console.log("Validation Error:", error.errors);
  });

Explanation:

  • validate(userData) → checks the object against the schema.
  • If valid, you get the cleaned object back (validData).
  • If invalid, the .catch block gives an array of error messages.

Different Validation Scenarios for Yup Object

The yup.object method is powerful because it allows you to define object schemas, apply constraints, handle null or undefined values, validate arrays of objects, and even work with dynamic keys. Below, we’ll walk through the most common use cases of yup.object, grouped by related scenarios.

Yup Schema for Required Object

const userSchema = yup.object({
  name: yup.string().required(),
  age: yup.number().required(),
});

Explanation:
This schema ensures that all required fields exist. Use this for yup object required validation when you need certain properties to be mandatory. Missing fields trigger validation errors, making it suitable for form submissions and API requests.

Handling Nullable, Undefined, or Empty Object

const addressSchema = yup
  .object({
    city: yup.string().required(),
    zip: yup.string().required(),
  })
  .nullable()
  .optional();

const notEmpty = yup.object().required().test("not-empty", "Object cannot be empty", obj => Object.keys(obj).length > 0);

Explanation:

  • .nullable() allows null values.
  • .optional() allows the object to be missing entirely.
  • .required() + .test() ensures that the object is not empty.
    This is useful for optional sections of forms or configurations where the object may or may not be provided.

Default Values for Object Properties

const settingsSchema = yup.object({
  theme: yup.string().default("light"),
});

Explanation:
Use default values when an object property is missing. This handles the yup object default value scenario and ensures your application has fallback values to maintain consistency.

Nested Object Validation

const profileSchema = yup.object({
  name: yup.string().required(),
  address: yup.object({
    city: yup.string().required(),
    zip: yup.string().required(),
  }),
});

This schema defines a nested object structure:

  • The outer object has a name property (required string).
  • The address property is itself an object with city and zip, both required strings.
  • This ensures that both the main object and its nested address object meet the defined rules.

Yup Object Error Handling

The yup.object method is the backbone of object validation in Yup. Whenever you define a schema using yup.object, the next step is to ensure proper error handling. Without capturing errors, you won’t know whether the object matches the expected structure. By handling validation errors effectively, you can make sure that invalid objects don’t break your application and that users see exactly what needs to be fixed.

Error handling with yup.object typically involves using .validate() and catching the resulting errors. With the option abortEarly: false, yup.object will report all validation errors inside the object instead of just stopping at the first one. This makes it ideal for forms or APIs where complete feedback is important.

userSchema
  .validate(userData, { abortEarly: false })
  .then((validData) => console.log("Valid Object:", validData))
  .catch((err) => console.log("Object Errors:", err.errors));

Explanation:

  • The option abortEarly: false ensures that every issue inside the object is reported.
  • The .catch block shows all the error messages collected from the yup.object validation process.

While this article focuses on Yup object validation, Yup can handle many other data types and scenarios. For a deeper look into all Yup capabilities, check out our Yup Deep Dive guide.

Conclusion

The yup.object method is the foundation of object validation in Yup. From handling required fields to optional data, from arrays of objects to nested objects, and from TypeScript integration to custom rules, yup.object is versatile enough to cover nearly all real-world use cases.

Whether you are working with forms, APIs, or complex data structures, mastering yup object validation ensures data consistency and fewer bugs.

Sharukhan Avatar

Sharukhan Patan

Sharukhan Patan is the founder of Tecktol. He has worked as a software engineer specializing in full-stack web development.

Popular Posts