How can my class-validator validate union string | number?
Asked Answered
G

1

7

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 ?

Gayl answered 17/5, 2022 at 10:21 Comment(0)
C
11

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;
}
Carlo answered 17/5, 2022 at 11:50 Comment(2)
I was wondering if it's possible to do it without custom validator, but if it's impossible thanks mateGayl
I looked around for other solution, but sadly did not find anything elseCarlo

© 2022 - 2024 — McMap. All rights reserved.