Using class-validator, validation pipes I would like to mark some fields as required. I tried using @IsNotEmpty method. It throws a 400 error when the input is empty. But i need to throw an error if input is missing as well.
DTO: Address Object with fields address1 and address 2. I would like to have address1 as required and address2 as optional
import {IsString, IsInt, IsNotEmpty } from 'class-validator';
import {ApiModelProperty} from '@nestjs/swagger';
export class Address {
@ApiModelProperty({description: 'Address Line 1', required : true})
@IsString()
@IsNotEmpty()
required : true
address1: string;
@ApiModelProperty({description: 'Address Line 2', required :false})
@IsString()
address2?: string;
}
// App.js: Application file where validation pipes are defined.
async function bootstrap() {
const expressServer = express();
const app = await NestFactory.create(AppModule, expressServer, {bodyParser: true});
app.use(bodyParser.json({limit: 6851000}));
app.useGlobalInterceptors(new UnhandledExceptionInterceptor());
app.useGlobalFilters(new HttpErrorsExceptionFilter());
app.useGlobalFilters(new UnhandledExceptionFilter(newLogger('UnhandledExceptionFilter')));
app.useGlobalPipes(new ValidationPipe({skipMissingProperties: true}));
app.useGlobalPipes(new ValidationPipe({forbidNonWhitelisted :true, whitelist:true, transform:true}));
}
Sample Input: Sample input with both the fields.
{
"shippingAddress": {
"address1":,
"address2": null
}
}
In this case this provides a 400 as expected, But I also need an error when input is like below missing one of required fields,
{
"shippingAddress": {
"address2": null
}
}