I have an simple DTO class for validation
class SearchIssuerDto {
search: string | number;
}
What is the correct way to validate the search param that it can accept an string or a number ?
I have an simple DTO class for validation
class SearchIssuerDto {
search: string | number;
}
What is the correct way to validate the search param that it can accept an string or a number ?
You can create a custom validator for that:
@ValidatorConstraint({ name: 'string-or-number', async: false })
export class IsNumberOrString implements ValidatorConstraintInterface {
validate(text: any, args: ValidationArguments) {
return typeof text === 'number' || typeof text === 'string';
}
defaultMessage(args: ValidationArguments) {
return '($value) must be number or string';
}
}
Usage:
class SearchIssuerDto {
@IsDefined()
@Validate(IsNumberOrString)
search: number | string;
}
© 2022 - 2024 — McMap. All rights reserved.