What is the best way to enable the acceptance of a null value during the validation process of an optional

Currently, I am in the process of assembling a sandwich. Whenever all the necessary details are provided to Nest, everything operates smoothly and flawlessly. However, my predicament arises when attempting to assign null (empty string) to an enum, resulting in failed validation.

// successful
const sandwich = {
    name: 'Turkey',
    ...
    pricing: {
        requirePayment: true,
        default: {
            value: 2000,
            unit: 'whole',
        }
    }
} 

// fails validation
const sandwich = {
    name: 'Turkey',
    ...
    pricing: {
        requirePayment: false,  // AKA free sandwich
        default: {
            value: "",
            unit: "",
        }
    }
} 

// create-sandwich.dto.ts

@ApiProperty({
    description: '',
    example: '',
  })
  @ValidateNested({
    each: true,
  })
  @Type(() => PricingInterface)
  @IsNotEmpty()
  readonly pricing: PricingInterface;
// pricing.interface.ts

@ApiProperty({
    description: '',
    example: '',
  })
  @ValidateNested({
    each: true,
  })
  @Type(() => DefaultPricingInterface)
  @IsOptional()
  readonly default: DefaultPricingInterface;
// default-pricing.interface.ts

@ApiPropertyOptional({
    description: '',
    example: '',
  })
  @IsEnum(PriceUnit)
  @IsOptional()
  readonly unit: PriceUnit;  // WHOLE, HALF

@ApiPropertyOptional({
    description: '',
    example: '',
  })
  @IsNumber()
  @IsOptional()
  readonly value: number;

An error message is being prompted:

"pricing.default.unit must be a valid enum value"

I comprehend the issue at hand, however, I'm uncertain on how to adhere to the validation rule. In cases where the sandwich is complimentary, no value will be designated to pricing.default.unit. Despite setting the property as optional, I would prefer to maintain the validation if attainable. How can I permit unit to be an empty string?

Your input or suggestions are warmly welcomed!

Answer №1

@IsOptional() indicates the absence of a value, specifically either null or undefined, rather than an empty string. To address the issue, pass a null or undefined, or simply leave out that field altogether instead of passing an empty string. It is even possible to omit the default field entirely since @IsOptional() has been specified for it as well.

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

Having trouble locating the .ts module when executing a Node script with experimental modules enabled

I am currently developing a node express project and I need to run a node script from the terminal. Within my project, there are some .ts files that I want to include in the script (MyScript.js). Below is the content of MyScript.js: import get from &apos ...

What are the most optimal configurations for tsconfig.json in conjunction with node.js modules?

Presently, I have 2 files located in "./src": index.ts and setConfig.ts. Both of these files import 'fs' and 'path' as follows: const fs = require('fs'); const path = require('path'); ...and this is causing TypeScr ...

Attempting to convert numerical data into a time format extracted from a database

Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here&apo ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Exploring the wonders of using the Async Pipe with Reactive Extensions

I'm facing a little issue with the async pipe in Angular. Here's my scenario: I need to execute nested observables using the async pipe in HTML because I'm utilizing the on-push change detection strategy and would like to avoid workarounds ...

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...

Utilize JSX attributes across various HTML elements

I'm looking for a solution to efficiently add JSX attributes to multiple elements. Here are the example attributes I want to include: class?: string; id?: string; style?: string; And here are the example elements: namespace JSX { interface Int ...

Steps for displaying a 404 page on a server-side rendered dynamic route following a client-side page transition

I'm currently developing a next.js project using Contentful as the Content Management System. My goal is to display a 404 page for a server-side rendered dynamic route after a client-side page transition. When I directly request the page (by entering ...

Tips for incorporating a mail button to share html content within an Angular framework

We are in the process of developing a unique Angular application and have integrated the share-buttons component for users to easily share their referral codes. However, we have encountered an issue with the email button not being able to send HTML content ...

Setting a maximum limit for selections in MUI Autocomplete

Code updated to display the complete script logic. I want to restrict the number of selections based on a value retrieved from the database, but in this example, I have set it to 3 manually. The error message I'm encountering is "Cannot read properti ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

Classify the array types based on their indexes within the map

Is there a way to efficiently access elements in TypeScript using a map with the correct type? When attempting this, an error is thrown due to the type from the map being number | string type Tuple = [number, number, string]; const y: Tuple = [1, 2, &apos ...

The attribute 'randomUUID' is not found within the 'Crypto' interface

I attempted to utilize the crypto.randomUUID function in my Angular app version 13.1, however, it does not seem to be accessible. When trying to use it, I encountered this error: TS2339: Property 'randomUUID' does not exist on type 'Crypto ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescrip ...

Utilizing useContext data in conjunction with properties

When using useContext in a component page, I am able to successfully retrieve data through useContext within a property. customColorContext.js import { createContext, useEffect, useState, useContext } from 'react'; // creating the context objec ...

Performing operations on information within a map function

While using toLocaleString within this map, I encountered an issue where only one of the payment.amount's returned formatted as currency. {props.paymentDates.map((payment, index) => ( <tr key={"payment-" + index}> <td>{i ...

Filtering an array dynamically in Typescript depending on the entered value

My task involves filtering arrays of objects based on input field values. Data data: [{ taskname: 'Test1', taskId: '1', status: 'Submitted' }, { taskname: 'Test2', taskId: '2', status: 'Re ...