Skip to content

Not getting validation errors #210

@may215

Description

@may215

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?

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