graphql: [GraphQL] Validation not working with @InputType

Bug Report

Current behavior

mutation CreateComment {
  createComment(postId: 1, input: { text: "" }) {
    text
  }
}

This is working, but shouldn’t, but @ArgsType is working, but i need @InputType

Input Code

@InputType()
export class CreateCommentInput {
  @Field()
  @IsNotEmpty({ message: "Comment text can't be blank." }) // @MinLength(1) also not working
  @MaxLength(10000, {
    message: 'Comment text must be shorter than 10000 characters.',
  })
  text!: string;
}

Expected behavior

I expect this to work and throw error when text is empty

Possible Solution

Environment


Nest version: 7.6.1
class-validator version: 0.12.2


About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (6 by maintainers)

Most upvoted comments

You’re missing essential decorators to tell class-validator and class-transformer how to handle the sub-class. Make your DoWorkArgs this and it will work as intended.

@ArgsType()
class DoWorkArgs {
  @Field(() => DoWorkInput)
  @Type(() => DoWorkInput)
  @ValidateNested()
  input!: DoWorkInput;
}

This is how class-transformer and class-valdiator are intended to work and not a problem within the Nest ecosystem.

You also need to give the proper type to the parameter in the query handler like so

@Mutation(() => Int)
  doWork(@Args({ type: () => DoWorkArgs }) { input }: DoWorkArgs) {
    num = input.num;
    return num;
  }

@jmcdo29 it doesn’t work for me https://github.com/IslamGamal88/scaleup what am i missing here?

@jmcdo29 it doesn’t work for me IslamGamal88/scaleup what am i missing here?

Please provide a clear minimum reproduction repository. There’s no need for a database here, it just muddies up the code

@jmcdo29 i updated the code, it is now just that.

You never bind the ValidationPipie.

Please use our Discord channel (Support). We are using GitHub to track Bug Reports, Feature Requests, and Regressions.