class-validator
和 nestjs
对我的 Http 请求执行 validation。我遇到了一个有趣的边缘情况,我不确定这是一个错误还是我的实现有问题。
我有两个端点:1)使用有效的电话号码创建数据,2)通过路由参数中的电话号码检索数据。看起来路由参数有更严格的验证。我正在使用
'US'
国际代码,因为我的应用程序尚不支持国际号码。这是我的实现:
使用电话号码创建数据
/* contact.dto.ts */
export class ContactDto {
@IsPhoneNumber('US')
public phoneNumber: string;
@IsNotEmpty()
@IsString()
public name: string;
}
/* contract.controller.ts */
@Controller('contacts')
export class ContactsController {
@Post()
async createContact (
@Req() request: Request,
@Res() response: Response,
@Body() newContact: ContactDto
) {
// save the data
}
// other methods
}
在
@Body()
注释中,我可以传入有效的 10 或 11 位电话号码(带或不带标点符号)。例如:
// all pass in @Body()
{ "phoneNumber": "18005550000", "name": "..." }
{ "phoneNumber": "8005550000", "name": "..." }
{ "phoneNumber": "1 (800) 555-0000", "name": "..." }
// don't pass in @Body()
{ "phoneNumber": "12345678", "name": "..." }
{ "phoneNumber": "123456789012", "name": "..." }
从电话号码获取数据
/* phonenumber.models.ts */
export class FindPhoneNumberParam {
@IsPhoneNumber('US')
public phoneNumber: string;
}
/* phone-numbers.controller.ts */
@Controller('phone-numbers')
export class PhoneNumbersController {
@Get(':phoneNumber')
async getPhoneNumber (
@Req() request: Request,
@Res() response: Response,
@Param() phoneNumber: FindPhoneNumberParam
) {
// look up and return phone number resource
}
// other methods
}
在
@Param()
注释中,必须为11位数字,并以'US'
国际代码开头。 1
我想这需要我在接下来的
// all pass in @Param()
{api}/phone-numbers/18005550000
{api}/phone-numbers/1(800)5550000
// don't pass in @Param()
{api}/phone-numbers/8005550000
{api}/phone-numbers/12345678
{api}/phone-numbers/123456789012
{api}/phone-numbers/98005550000
中传递
11
数字'US'
代码是有道理的,但对我来说,1
和@Body()
有不同的行为似乎很奇怪他们使用相同的 @Param()
注释 - class-validators
。有谁知道为什么会出现这种情况?
@IsPhoneNumber