【问题标题】:class-validator in nestjs has unexpected behavior for phone numbers in body or routeNestjs 中的类验证器对正文或路由中的电话号码有意外行为
【发布时间】:2020-05-17 02:39:46
【问题描述】:

我正在使用 class-validatornestjs 在我的 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位数字,以1开头的'US'国际码。

// 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。有谁知道为什么会这样?

【问题讨论】:

    标签: typescript nestjs class-validator


    【解决方案1】:

    更新参数应该可以解决问题。不正确的解析是因为参数没有将其解析为字符串,而在正文中您将其显式传递为字符串

    export class FindPhoneNumberParam {
      @Transform(value => value.toString())
      @IsPhoneNumber('US')
      public phoneNumber: string;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多