Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question: get constrains in decorators and not the message #2433

Open
ako-v opened this issue Mar 12, 2024 · 1 comment
Open

question: get constrains in decorators and not the message #2433

ako-v opened this issue Mar 12, 2024 · 1 comment
Labels
type: question Questions about the usage of the library.

Comments

@ako-v
Copy link

ako-v commented Mar 12, 2024

I am trying to customize messages in nestjs response, I am using decorators in DTOs, and want to get min constraint I pass to @Min (this is just an example). My DTO is something like this:

class GetUsersDto {
  @ApiProperty({ required: false })
  @IsOptional()
  @Min(1, { message: 'validation.min' })
  @IsInt()
  @Transform((param) => parseInt(param.value, 10))
  page?: number;
}

in nestjs I am getting the validation error that comes from class-validator, but I get only "validation.min" as the constraint:

app.useGlobalPipes(
    new ValidationPipe({
      stopAtFirstError: true,
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      exceptionFactory: (errors) => {
        console.log(errors);
        const result = errors
          .map((error) => {
            const key = Object.values(error.constraints)[0];
            const message = getMessage(key, error); // I get the customized message from the message I provided to `@Min`
            return message ? message : getMessage('validation.400'); 
          })
          .join('');
        return new BadRequestException(result);
      },
    }),
  );

in the console.log(errors), I get something like this:

[
ValidationError {
  target: GetUsersDto { page: -1 },
  value: -1,
  property: 'page',
  children: [],
  constraints: { min: 'validation.min' }
}
]

As you see I get validation.min (the message) I passed as the constraint, the question is how can I get the value (here is 1) I passed to @Min?

@ako-v ako-v added the type: question Questions about the usage of the library. label Mar 12, 2024
@emir-gradient
Copy link

emir-gradient commented Mar 18, 2024

Hello.

In your custom validator, you can utilize snippet similar to this one:

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

// ... Some other code
const dataType = CreateAdminDTO; // you put your data type here (one you are validating). I think you can use ValidationError.target for this.
const metadataStorage: MetadataStorage = getMetadataStorage();
const metas = metadataStorage.getTargetValidationMetadatas(dataType, null, false, false);

console.log(metas);

// Result is like:
//   [
// ValidationMetadata {
//   groups: [],
//   each: false,
//   context: undefined,
//   type: 'customValidation',
//   name: 'minLength',
//   target: [class CreateAdminDTO],
//   propertyName: 'username',
//   constraints: [ 4 ], => validator was @minLength(4)
//   constraintCls: [class CustomConstraint],
//   validationTypeOptions: undefined
// },
// ... other metadatas
// ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

2 participants