question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

question: can we perform a oneOf validation?

See original GitHub issue

Description

How to perform a oneOf validation of a nested object i.e., child object is either of TypeA or TypeB? This seems like a very common use case, is there an out-of-the-box solution for this? I understand that this problem is concerning class-transformer more than it is class-validator

Is there an example of a generic @OneOf()decorator? Any ideas on how to work with class-transformer and class-validator together to make this happen?

Reproduction

class TypeA {

    @IsString()
    public foo;
}

class TypeB {

    @IsString()
    public bar;
}

class Parent {

    @IsObject()
    @ValidateNested()
    @Type((): Function => TypeA)  // ???
    public child: TypeA | TypeB;
}

Environment

  • nodejs: 8.11.2
  • browser
  • framework/library

class-validator version: 0.12.2

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:7
  • Comments:9 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
ibraah88commented, May 30, 2020

@mehtamanan can you try this ?

import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
  ValidationArguments,
} from 'class-validator';
import { activitiesList } from '../activitiesList';

@ValidatorConstraint({ async: true })
export class OneOfConstraint implements ValidatorConstraintInterface {
  validate(activities: any, args: ValidationArguments) {
   return Array.isArray(activities)
      ? activities.every(item => activitiesList.includes(item))
      : false;
  }
}

export function OneOf(validationOptions?: ValidationOptions) {
  return function(object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: OneOfConstraint,
    });
  };
}

and to use it in your DTO

...
import { activities } from '../activities';
...

  @IsArray()
  @IsNotEmpty()
  @OneOf({
    message: `activities must be in: ${activities}`,
  })
  activities: string[];
0reactions
github-actions[bot]commented, Dec 17, 2022

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

validation of json schema having oneOf keyword
The schema in my question was incorrect. The schema meant match oneOf(all three references), email, rememberme_id, buyer_account_number. The data (email and ...
Read more >
Multiple JSON Schemas with *oneOf* - M100 - MongoDB
Here oneOf is a keyword construct in the JSON Schema, which is used to provide an array of criteria where, if exactly one...
Read more >
Frequently Asked Questions - Ajv JSON schema validator
# Why Ajv validates empty object as valid? ... "properties" keyword does not require the presence of any properties, you need to use...
Read more >
It all starts with applicability - JSON Schema Fundamentals ...
"Validation begins by applying the root Schema to the complete instance document. Applicator keywords apply subschemas to the instance ...
Read more >
Frequently Asked Questions - Schemathesis - Read the Docs
Input validation is, therefore, more frequently examined than other parts. ... As the first step, you can use schema generators like flasgger for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found