Yup Object: .defined() Method, Difference from .required() Validation


Yup object refers to a schema-based way of validating JavaScript objects by defining the shape, allowed keys, and validation rules for each property.

The yup.object() schema is specifically designed to define the structure of JavaScript objects, including required and optional keys, nested object shapes, default values, and strict property checks.

Using Yup object validation, developers can enforce predictable object structures, handle nested object validation, manage dynamic keys, and ensure type-safe data in forms or API payloads, making it indispensable for real-world applications where object consistency matters.

Ready to dive deeper into defining structured objects, validating data, handling errors, and managing different edge case scenarios with yup.object()? Continue exploring the sections below to master real-world Yup object validation and ensure your applications handle data reliably.

Try it Yourself: Code Example

yup.object({company: yup.string()})

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.

Understanding .defined() and .required() in Yup Objects

The .defined() method in Yup ensures that a field is explicitly defined, even if its value is null or undefined. Unlike .required(), it doesn’t enforce a non-empty value but guarantees that the property exists in the object. This is especially useful when you need to maintain consistent object shapes for API payloads or form state, ensuring that optional fields don’t disappear unexpectedly.

The .required() method enforces that a field has a value and cannot be undefined or null. It is commonly used in forms and API validation to make sure essential data, such as user email or password, is always provided. Yup object validation with .required() helps prevent missing or incomplete data in real-world applications.

Understanding the difference between .defined() and .required() is crucial for precise object validation:

  • .defined(): Ensures the key exists, but allows null or empty values.
  • .required(): Ensures the key exists and has a non-empty value.

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.

Summary

The yup.object() method provides a structured and reliable way to define, validate, and handle JavaScript objects. It allows developers to enforce required and optional fields, manage nested objects, set default values, and handle different edge case scenarios.

Understanding the distinction between .defined() and .required() ensures precise control over object properties, while proper error handling with .validate() prevents invalid data from breaking applications.

By mastering Yup object validation, you can maintain consistent, type-safe data across forms, API requests, and complex application structures, making your applications more robust and reliable.

Author

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