class-validator
class-validator copied to clipboard
How to read the declared metadata on a field or prop ?
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!
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;
}
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; }
Unfortunately, this solution does not work at the moment.
Is there any update on this? We are looking to generate a form using this metadata, as we have a mono-repo, all of our types are easily accessible between our frontend/backend apps, figured there must be a way to get the decorator data somehow, has anyone figured this out?
We do not expose the metadata about classes officially but you can access it. Keep in mind that this API is considered private and can break without any mention in the changelog.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.