Skip to content

Instantly share code, notes, and snippets.

@illusi03
Last active May 4, 2024 01:10
Show Gist options
  • Save illusi03/03bf943a0dd958b1771c239430da4833 to your computer and use it in GitHub Desktop.
Save illusi03/03bf943a0dd958b1771c239430da4833 to your computer and use it in GitHub Desktop.
Article Medium - Enhanced validation in Nest.js - STEP-5
import { Type } from 'class-transformer';
import { IsEmail, IsNotEmpty, ValidateNested } from 'class-validator';
class AddressCustomerType {
@IsNotEmpty()
city: string;
@IsNotEmpty()
address: string;
}
export class CreateCustomerDto {
@IsNotEmpty()
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
@IsNotEmpty()
@ValidateNested()
@Type(() => AddressCustomerType)
address: AddressCustomerType;
}
export const exceptionFactory = (errors: ValidationError[]) => {
const errorValidation = {};
let errorMessages = [];
const parseErrorMessage = (errObject, propertyKey) => {
const isNested =
typeof errObject?.children !== 'undefined' &&
errObject?.children.length > 0;
if (!isNested) {
const messages = Object.values(errObject?.constraints);
errorValidation[`${propertyKey}`] = [...messages];
errorMessages.push(messages); // Default property message error
return true;
}
errObject?.children.map((valChild) => {
const nextPropertyKey = `${propertyKey}.${valChild.property}`;
parseErrorMessage(valChild, nextPropertyKey);
});
};
errors.forEach((err) => {
parseErrorMessage(err, err.property);
});
errorMessages = errorMessages.flat(1); // Default property message error
return new ValidationException(errorValidation, errorMessages);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment