简体   繁体   中英

How can I allow a null value when validating an optional field?

I am trying to create a sandwich. When all values are passed to Nest, everything works great . Where I'm running into trouble is passing null (empty string) to an enum and rightfully so, that fails 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;

The error I am getting is:

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

I understand the error, but I'm not sure how to satisfy the validation rule. If the sandwich is free, it won't have a value for pricing.default.unit . I have set the property as optional & I would like to keep the validation if possible. How can I allow unit to be an empty string?

Thank you for any suggestions!

@IsOptional() means null or undefined , not empty string. Pass a null or undefined , or completely omit that field, instead of passing an empty string would solve the problem. You can even completely omit the default field as you have also declared @IsOptional() for default .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM