Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda