Skip to content

question: how to have the validate function called for custom validation decorators? #1943

@nicostubi

Description

@nicostubi

I was trying to use a custom validation decorators

  • Added the following source code in my project, as documented here :

ValidationConstraint and decorator

import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
  ValidationArguments,
} from 'class-validator';

@ValidatorConstraint({ async: true })
export class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface {
  validate(userName: any, args: ValidationArguments) {
    console.log('validate')
    throw new Error('validate')
  }
}

export function IsUserAlreadyExist(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsUserAlreadyExistConstraint,
    });
  };
}

And put it to use on my NestJS - GraphQL backend:

@InputType()
export class UserInput {
	@Field(() => String, { nullable: true })
	@IsUserAlreadyExist()
	username: string
}

The problem:
I sent a postman request, my mutation is processed as usually and the user can be created.

However, I never pass inside the validate function. No console.log displayed. No error thrown by my backend...

Am I supposed to call it somehow manually?

Like the usage in the documentation, ie call validate on the object? (BTW, adding the call to validate didn't result in an error, so I still have the problem of validate function of my IsUserAlreadyExistContraint not being called...)

validate(post).then(errors => {
  // errors is an array of validation errors
  if (errors.length > 0) {
    console.log('validation failed. errors: ', errors);
  } else {
    console.log('validation succeed');
  }
});

If it must be called manually, isn't there any way to have the validation done automatically?

BR
Nicolas

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions