'Allow property to be an array or plain type
I was trying to be able to pass the property as an array of strings or just a string value.
class GetUsersDTO {
// @IsArray() | @IsString()
readonly status;
}
But it's not possible even though it's a common use case. Can we do it with a plain class-validator package?
Solution 1:[1]
You'll need to make your own custom validator for this. Typescript doesn't reflect generics (yes, a union type is a special generic) and because of that, class-validator won't be able to properly figure out which of the two decorators to use.
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
@ValidatorConstraint({ name: 'customText', async: false })
export class IsArrayOrString implements ValidatorConstraintInterface {
validate(val: string | string[], args: ValidationArguments) {
const isArray = Array.isArray(val);
const isString = typeof val === 'string';
return isArray || isString
}
}
And now you can use it like
class GetUsersDTO {
@Validate(IsArrayOrString)
readonly status: string | string[];
}
My personal word of warning: using multiple allowed inputs to the same endpoint usually brings nothing but trouble and headache. If possible, keep them separate.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jay McDoniel |
