Search code examples
typescriptnestjstypeormclass-validator

How can my class-validator validate union string | 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 ?


Solution

  • 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;
    }