class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

Not getting validation errors

Open may215 opened this issue 8 years ago • 5 comments

Hi, I am trying to use this package and I am not getting any errors when it should be: Here is an example of my code where I should get error on empty 'username' parameter.

I am using typeorm, typedi, routing-controllers

The user model/entity:

import {Column, Entity, Index, PrimaryColumn} from 'typeorm';
import {IsEmail, IsNotEmpty} from 'class-validator';

@Entity('User', {schema: 'vacayz'})
@Index('index_user_on_username', ['username'], {unique: true})
export class User {

    @PrimaryColumn()
    @Column('int', {
        nullable: false,
        primary: true,
        name: 'id',
    })
    public id: number;

    @IsEmail()
    @IsNotEmpty()
    @Column('varchar', {
        nullable: false,
        length: 255,
        name: 'username',
    })
    public username: string;
}

The API controller:

import {
    Body, JsonController, Post
} from 'routing-controllers';

import { GeneralError } from '../errors/GeneralError';
import { User } from '../models/User';
import { UserService } from '../services/UserService';
import {validate} from 'class-validator';

@JsonController('/users')
export class UserController {
    constructor(
        private userService: UserService
    ) { }

    @Post()
    public create( @Body({ required: true, validate: true }) user: User): Promise<User | GeneralError> {
        validate(user).then(err => {
            console.log(err);
            if (err.length > 0) { **// No Errors here**
                console.log('validation failed. errors: ', err);
                return undefined;
            } else {
                console.log('validate success');
                return this.userService.create(user);
            }
        });
        return undefined;
    }
}

The call to the API:

curl -X POST \
  http://localhost:3000/api/users \
  -H 'content-type: application/json' \
  -d '{"id": "1234567890", "username": ""}'

What do I missing here?

may215 avatar May 31 '18 12:05 may215

Hi, I am facing the same problem with a really similar problem setup. Have you solved the issue?

PelayoChoya avatar Jun 08 '18 17:06 PelayoChoya

Do you have class-transformer features enabled in routing-controllers?

MichalLytek avatar Jun 08 '18 19:06 MichalLytek

Solved, the problem was not class-validator's fault.

I was using nestjs without integrating a ValidationPipe ( a validation pipe implements the class-validator): https://docs.nestjs.com/pipes

PelayoChoya avatar Jun 12 '18 11:06 PelayoChoya

Closing this as solved.

NoNameProvided avatar Jul 18 '18 20:07 NoNameProvided

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Jul 25 '18 21:07 lock[bot]