【问题标题】:URL input validation NestJsURL 输入验证 NestJs
【发布时间】:2021-05-25 20:08:26
【问题描述】:

我正在尝试对网站 URL 进行输入验证。我使用了 URL 装饰器,但是当我不输入任何 URL 时,它会给我错误消息。我应该怎么做才能让它也接受空字符串?

  @ApiProperty()
  @IsString()
  @IsUrl(undefined, { message: 'Company URL is not valid.' })
  companyURL: string;

【问题讨论】:

  • 为什么要将undefined作为参数传递给@IsUrl装饰器?

标签: node.js nestjs class-validator


【解决方案1】:

您可以使用@IsOptional() 类验证器或@IsDefined(value: any)

@IsOptional()

检查给定值是否为空(=== null,=== 未定义),如果是,则忽略属性上的所有验证器。

@IsDefined(value: any)

检查值是否已定义(!== undefined, !== null)。这是唯一忽略 skipMissingProperties 选项的装饰器。

如果您需要有关它的更多信息,请查看documentation about class-validators

【讨论】:

    【解决方案2】:

    您可以使用@IsOptional() 类验证器来检查给定值是否为空。

    @ApiProperty()
    @IsOptional()
      @IsString({ message: 'Must be a string!' })
      @IsUrl(undefined, { message: 'Company URL is not valid.' })
      companyURL: string;
    

    您还可以从“https://github.com/typestack/class-validator#usage”或“https://github.com/typestack/class-validator#validation-decorators”查看更多信息。

    【讨论】:

      【解决方案3】:

      我必须添加 @Validateif() 来检查它是否有值。

      @ApiProperty()
        @ValidateIf(o => o.  companyUrl
          === 'value')
        @IsString()
        @IsUrl(undefined, { message: 'Company Url is not valid.' })
        companyUrl: string;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-15
        • 1970-01-01
        • 1970-01-01
        • 2018-02-28
        • 1970-01-01
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多