Class-validator: How to read the declared metadata on a field or prop ?

Created on 27 May 2019  路  3Comments  路  Source: typestack/class-validator

Hi,

is there a way to get the initially declared Metadata on a decorator ?,
For example with the MaxLength decorator. MaxLength(255, { message: "somemessage" }) ,
i am looking for a way to retrive that 255 .

Thanks alot!

question

Most helpful comment

I'm also interested in this, I'm trying to generate forms with required fields using the @IsDefined decorator metadata.

All 3 comments

I'm also interested in this, I'm trying to generate forms with required fields using the @IsDefined decorator metadata.

You have to use internal API to get this kind of data. Check a code and how internally class-validator works/store data you need.

Hey again,

I spent a bit of time looking at this today and the best I could come up with is the following:

import { getFromContainer, MetadataStorage } from 'class-validator';

const validatorStorage: MetadataStorage = getFromContainer(MetadataStorage);

const createUserDtoValidationMetadata = validatorStorage.getTargetValidationMetadatas(CreateUserDto, null, null);

console.log(validatorStorage.groupByPropertyName(createUserDtoValidationMetadata));

For reference here is what the CreateUserDto looks like:

export class CreateUserDto {
    @IsString({
        message: 'Name must be a text value'
    })
    name: string;
    @IsString({
        message: 'Surname must be a text value'
    })
    surname: string;
    @IsString()
    @IsOptional()
    password?: string;
    @IsEmail()
    email: string;
    @IsString()
    type: UserType;
    @IsOptional()
    @IsString()
    cellphoneNumber?: string;
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

otbe picture otbe  路  5Comments

isergey picture isergey  路  3Comments

ibox4real picture ibox4real  路  4Comments

TomMarius picture TomMarius  路  3Comments

jerradpatch picture jerradpatch  路  5Comments