Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

275
Visualizações
Create custom validation decorator : how it works?

I want to create a custom decorator but I think i don't really understand how it works ! At first I began to validate all not null fields.

E.G :

    @AllowNull(false)
    @Validate({
        notNull: {
            msg: 'zip code is required',
        },
    })
    @Column({
        type: DataType.STRING,
    })
    zip_code: string;

But then I thought "DRY principle is not really applicable there, how can you make a custom validator ?"

I tried a few things class-validator is one of them. But I didn't manage to make it work as intended.

When sending a request with a null zip_code, custom validation Decorator is not triggered than this field is set to null into the DB for this record (on create or update)

The best thing I manage to do at this time is

//required.ts
export function required(field) {
    return {
        notNull: {
            msg: `${field} is required.`,
        },
    };
}

I just return the object which @Validate needs to output the correct message

    @Validate(required('zip_code'))
    @Column({
        type: DataType.STRING,
    })
    zip_code: string;

I began using Nest a few days ago. I'm not really familiar with it. I'm pretty sure there's an easy way. That's why I'm asking the question here

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Solution was simply to use validate method from 'class-validator' in my service

//required.ts
import { registerDecorator } from 'class-validator';

export function Required(property: string) {
    return function (object, propertyName: string) {
        registerDecorator({
            name: 'isRequired',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [property],
            // Not the best way but it works, i'll update the answer later ;)
            options: {
                message: '$property is required',
            },
            validator: {
                validate(value: any) {
                    return value !== null;
            },
        });
    };
}
// CompanyService.ts
    create(createCompanyDto: CreateCompanyDto) {
// Instead of Model.create use Model.build then Model.save after validate
        const company = Company.build(createCompanyDto);
        return validateOrReject(company, {
            validationError: { target: false },
        })
            .then(() => company.save())
            .catch((errors) => errors);
    }
// company.entity.ts
// there you can call the decorator
    @Required('city')
    @Column({
        type: DataType.STRING,
    })
    city: string;

My mistake was to use Model.create or Model.update instead of build then validate

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda