Search code examples
typescriptnestjsdtoclass-validator

How to Validate Array of Urls using Class-Validator?


I am using Class-Validator to validate Properties of DTOs for Nest.js Application. In there I have a Property "images", which is an Array of Strings and those Strings are Urls. So, I want to validate each and every Url in that Array.


class SomeDto {
// ...
       
// Array of Urls
@IsArray()
@IsUrl({each:true})
images: string[];

// ...
}

But this doesn't seem to work. Does anyone know how to validate this Array of Urls.


Solution

  • The type of the first parameter of IsUrl is not the usual ValidationOptions one.

    You can check its signature:

    export declare function IsUrl(options?: ValidatorJS.IsURLOptions, validationOptions?: ValidationOptions): PropertyDecorator;
    

    So, try to pass the { each: true } in the second place and it will work.

    class SomeDto {
    // ...
           
    // Array of Urls
    @IsArray()
    @IsUrl({}, { each: true })
    images: string[];
    
    // ...
    }