Ensuring that an object containing optional values meets the condition of having at least one property using Zod validation

When using the Zod library in TypeScript to validate an object with optional properties, it is essential for me to ensure that the object contains at least one property. My goal is to validate the object's structure and confirm that it adheres to a specific format while still allowing certain properties to be optional.

Consider the following example representing the structure of the object I am dealing with:

interface MyObject {
  prop1?: string;
  prop2?: number;
  // Additional optional properties...
}

I am looking for a way to utilize Zod in defining a validation schema that permits optional properties but mandates that at least one property must be present within the object.

How can this requirement be met using Zod? Any advice or code snippets demonstrating how to establish such a schema and subsequently validate the object would be greatly appreciated.

Previously, I attempted to define the schema as shown below:

z.object({
  prop1: z.string().optional(),
  propt2: z.string().optional(),
});

However, there were instances where the validation did not account for data absence, resulting in acceptance even when no data was provided.

Answer №1

To ensure that an object has at least one property, you can create a custom refinement by checking that no values are set to undefined

const bar = z.object({
  prop1: z.string().optional(),
  propt2: z.string().optional(),
}).refine((obj) => {
  for (const value of Object.values(obj)) {
    if (value !== undefined) return true;
  }
  return false;
}, { 
  message: "Object must have at least one defined property"
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to access UserProfile in a different Dialogio

For the implementation of a chatbot, I am utilizing Microsoft's Bot Builder framework. However, upon implementing an alternative path to the dialog flow, I noticed that the user's Profile references are getting lost. Here is the code snippet fr ...

The Typescript hello world example encounters an issue with Karma

Recently, I encountered an issue while working on a TypeScript project with Jasmine and Karma. It seems that Karma is unable to execute the compiled unit tests due to an error showing up in Chrome: Uncaught ReferenceError: define is not defined To illust ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

Error: When trying to run the `ng build` command in Git Bash, TypeScript module cannot be

When attempting to execute ng build using Git Bash, I encountered this error message, even though I had previously executed npm install -g typescript. Where should I place the typescript installation so that Git can detect it? Error $ npm install -g typ ...

The 'roleName' property is not found within the 'never' data type

// ** React Component and Library Imports import { useEffect, useState } from 'react' import Box, { BoxProps } from '@mui/material/Box' import Button from '@mui/material/Button' import Drawer from '@mui/material/Drawer&ap ...

How can I extract just the initial 2 letters of a country name using AmCharts maps?

Having trouble with Amcharts maps. I have a map that displays countries as United States, but I only want them to show as US. Is there a country formatter available for this issue? Any help is appreciated. ...

What is the proper way to define the type for a functional React component by using object destructuring on props?

As I continue to learn TypeScript and work on declaring advanced types, I am faced with converting my CRA project to TypeScript. Within this project, I have a component that closely resembles examples from react-router-dom, but I have not come across any T ...

Angular TypeScript test checking file size with Jasmine

Seeking optimal method for testing File size during input type="file" change event. Currently, my test specification appears as follows: it('attach file with too large size', () => { const file: File = { name: 'filename', ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

Generate detailed documentation for the functional tests conducted by Intern 4 with automated tools

I need to automatically generate documentation for my Intern 4 functional tests. I attempted using typedoc, which worked well when parsing my object page functions. However, it failed when working with functional test suites like the one below: /** * Thi ...

How can I make sure that another function will only be executed after the completion of a function in

I'm currently working on an app with Angular CLI, and I am trying to retrieve a list after an insertion. Despite trying various methods such as observer, promise, async, setTimeout, etc., I haven't been able to find the right solution yet. I feel ...

Cannot establish a connection with Socket.IO

I've encountered an issue with establishing a connection to Socket.IO in my node server. Although the server starts successfully with Socket.IO, I am not seeing any console logs when trying to connect to Socket. this.server.listen(this.port, () => ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Having trouble resolving modules after generating tsconfig.json?

I recently added a tsx component to my next.js 13 project following the documentation. After creating the required tsconfig.json file, I encountered module not found errors when running npm run dev: $ npm run dev > [email protected] dev > n ...

Typescript function incorrectly returns Protractor's "element.all" output as Promise<string> instead of Promise<string[]>

Kindly review the code snippet provided below. The function getAllGroupIds() is designed to return an array of IDs belonging to "group" elements. The goal is to retrieve all the group-ids both before and after a test action, in order to compare them. Howe ...

Dealing with a void method in a React unit test by treating it as an object's property

How can I pass a value to a function in an interface to trigger a click event on an element? I have a React component that I want to write unit tests for: const VariantItem = (props: VariantItem): ReactElement => { return ( <div key={props.produc ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

Unable to find '.file.scss' in the directory '../pages'

I am currently in the process of migrating my Ionic 3 app to version 4. However, I have encountered an issue where some pages are not recognizing the SCSS file from the TypeScript component. @Component({ selector: 'car-id', templateUrl: &apo ...

Enhancing the loading speed of hefty Angular components

The issue I encountered involved a large component that loads over 1000 data elements, populated by a service called only once. Initially, the service was being called each time the component initialized, which seemed to be causing performance problems. To ...

Encountering a tslint issue: "Parsing error: Expression expected"

Could someone provide some insight on this issue? I’m encountering an error message that says Failed to compile. Parsing error: Expression expected with this specific line of code - isLogViewVisible: dashboard?.logView !== null where the variable isLog ...