【发布时间】:2019-11-30 21:32:23
【问题描述】:
使用类验证器,验证管道我想根据需要标记一些字段。我尝试使用@IsNotEmpty 方法。当输入为空时,它会抛出 400 错误。但是如果输入也丢失了,我也需要抛出一个错误。
DTO:地址对象,字段为地址 1 和地址 2。我希望地址 1 为必需,地址 2 为可选
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}));
}
示例输入:包含两个字段的示例输入。
{
"shippingAddress": {
"address1":,
"address2": null
}
}
在这种情况下,这提供了预期的 400,但是当输入如下所示缺少必填字段之一时,我也需要一个错误,
{
"shippingAddress": {
"address2": null
}
}
【问题讨论】: