Skip to content

Validation dosn't work #1742

Open
Open
@JudgEby

Description

@JudgEby

When adding a sequelize-typescript's decorator to the model field, which should check that the field is not empty, validation does not work and allows you to create a record without passing this field. DB is Postgres

Create function in client.repository.ts:

async create(values) {
        return this.model.create(values, {
            validate: true,
            ...options,
        });
    }

Client model:

import {
    Table,
    Column,
    Model,
    DataType,
    PrimaryKey,
    ForeignKey,
    BelongsTo,
    HasMany,
    Unique,
    IsEmail,
    Length,
    NotEmpty,
} from 'sequelize-typescript';
import { nanoid } from 'nanoid';
import { Company } from './company.model';
import { Invoice } from './invoice.model';

@Table
export class Client extends Model {
    @PrimaryKey
    @Column({
        type: DataType.STRING,
        defaultValue: nanoid,
    })
    id!: string;

    @Unique
    @NotEmpty
    @IsEmail
    @Column
    email!: string;

    @NotEmpty
    @Length({ min: 3, max: 30 })
    @Column
    firstName!: string;

    @NotEmpty
    @Length({ min: 3, max: 30 })
    @Column
    lastName!: string;

    @ForeignKey(() => Company)
    @NotEmpty
    @Column({
        type: DataType.STRING,
    })
    companyId!: string;

    @BelongsTo(() => Company)
    company!: Company;

    @HasMany(() => Invoice)
    invoices?: Invoice[];
}

If I try add custom validation:

@Is('not-empty', (value) => {
        console.log('custom decorator @Is not-empty value:', value);
        if (!value) {
            throw new Error('First name is required');
        }
    })
    @Column({ validate: { notEmpty: true } })
    firstName!: string;

It doesn't work too and there is no message in console.

Why walidation doesn't work?

P.S. If I send the firstName (for example) with a string length from 1 to 2 units, then the @Length({min: 3, max:30 }) validation works and an error is received.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions