Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!