When using @ValidateNested()
with the class-validator
library, I encountered a formatting issue when validating a nested object:
// Object Schema:
export class CreateServerSettingsDTO {
@IsNotEmpty({ message: 'Username is required' })
username: string;
@IsNotEmpty({ message: 'Password is required' })
password: string;
}
export class CreateServerDTO {
@IsNotEmpty({ message: 'Server name is required' })
serverName: string;
description?: string;
@ValidateNested()
@Type(() => CreateServerSettingsDTO)
@IsObject({ message: 'Settings must be an object' })
@IsNotEmpty({ message: 'Settings are required' })
settings: CreateServerSettingsDTO;
}
// Validation response:
{
"statusCode": 400,
"message": [
"settings.Username is required",
"settings.Password is required"
],
"error": "Bad Request"
}
I am looking to customize the validation messages for the nested object under settings
. Specifically, I want the messages to display as:
{
"statusCode": 400,
"message": [
"Username is required",
"Password is required"
],
"error": "Bad Request"
}
I have tried different approaches but could not find a way to remove the settings.
prefix from the nested property messages. Any suggestions on how this can be accomplished?