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
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