标签: class-validator

是否可以验证单个路由参数?

假设我有以下路线:

companies/{companyId}/departments/{departmentId}/employees
Run Code Online (Sandbox Code Playgroud)

是否可以分别验证两个资源 id ( companyId, departmentId) ?我尝试过关注,但没有成功。

class ResourceId {
  @IsNumberString()
  @StringNumberRange(...) // my custom validator
  id: number;
}

@Get(':companyId/departments/:departmentId/employees')
getEmployees(
  @Param('companyId') companyId: ResourceId,
  @Param('departmentId') departmentId: ResourceId,
) {}
Run Code Online (Sandbox Code Playgroud)

当单个路由中有多个参数时,我遇到了多种情况。我不想为每条路线创建单独的验证类。有没有办法以不同的方式处理这个问题?

javascript node.js typescript class-validator nestjs

5
推荐指数
2
解决办法
6343
查看次数

使用 class-validator 验证类中的一个字段

假设我有一个基于文档中示例的类(https://github.com/typestack/class-validator#usage

import {MinLength, MaxLength, validate} from "class-validator";

export class Post {

    @IsString()
    body: strong;

    @IsString()
    title: string;

    //...many more fields

    public async validate(){
        validate(this, { forbidUnknownValues: true, validationError: { target: false } });
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建此类的一个实例并向字段分配值。

const post = new Post()
post.body = 'body'
post.title = 'title'
// ... assign all the other fields
Run Code Online (Sandbox Code Playgroud)

我想验证post,跳过除 之外的所有字段的验证title。除了将组分配给所有字段之外,似乎没有其他方法可以做到这一点,而我不想这样做。有没有办法只验证这个单一字段?

typescript class-validator

5
推荐指数
1
解决办法
4615
查看次数

使用 class-validator 动态设置验证组

假设我有一堂这样的课

import {Min, Length, IsNotEmpty} from "class-validator";
 
export class User {
 
    @Max(10, {groups: ["child"]})
    @Max(100, {groups: ["adult"]})
    @Min(11, {groups: ["adult"]})
    age: number;
 
    @IsNotEmpty({groups: ["child", "adult"]})
    birthYear: number;

    @Length(2, 20, {groups: ["child", "adult"]})
    name: string;
}
Run Code Online (Sandbox Code Playgroud)

我可以通过这样做来验证这一点

import { validate } from 'class-validator'
User user = new User()
user.age = 15
user.birthYear = 2005
user.name = 'name'
validate(user, groups: ["adult"])
Run Code Online (Sandbox Code Playgroud)

我想做的是根据birthYear 字段动态设置用于验证的组。ValidateIf 不是我想要使用的东西,因为可能有很多字段和潜在的复杂条件。

看来我必须首先验证birthYear 字段以确保它满足给定的验证要求。这将要求我为birthYear创建一个独立的类,纯粹出于验证目的,因为似乎没有一种方法可以单独验证一个字段。如果 BirthYear 通过验证,我将使用它来确定要使用的验证组。

这感觉有点矫枉过正,而且工作量很大。有没有一种方法可以添加基于birthYear的验证组,而无需事先验证birthYear,或将其验证为单个字段?

validation dynamic typescript class-validator

5
推荐指数
0
解决办法
4133
查看次数

Nestjs applyDecorators用于多个装饰器

我想创建自定义装饰器并applyDecorators导入自@nestjs/common

...

applyDecorators(
  @Field(),
  @MinLength(2)
)

...
Run Code Online (Sandbox Code Playgroud)

但我遇到了 Typescript lint 错误。如何创建一个包含多个装饰器的自定义装饰器?

https://docs.nestjs.com/custom-decorators

"class-validator": "^0.11.0"
"@nestjs/common": "^7.0.9"
Run Code Online (Sandbox Code Playgroud)

class-validator nestjs class-transformer

5
推荐指数
1
解决办法
6617
查看次数

类验证器使用 createQueryBuilder 意外触发验证

我将Typeorm与class-validator结合使用,所以我定义了一个像这样的实体:

import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    BaseEntity,
    BeforeInsert,
    BeforeUpdate,
    getRepository
} from "typeorm";
import {
    validateOrReject,
    IsDefined,
} from "class-validator";
import errors from 'restify-errors';

@Entity()
export class License extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    public id!: string;

    @Column({ nullable: false })
    @IsDefined({ message: 'name field was not provided' })
    public name!: string;

    @Column({ nullable: false })
    @IsDefined({ message: 'description field was not provided' })
    public description!: string;

    @BeforeInsert()
    @BeforeUpdate()
    async validate() {
        await validateOrReject(this, { skipUndefinedProperties: true });

        // …
Run Code Online (Sandbox Code Playgroud)

validation restify typescript typeorm class-validator

5
推荐指数
1
解决办法
2274
查看次数

使用 class-validator 验证数字 18.2

我需要number 18.2使用class-validator进行验证。在当前阶段,我知道如何仅验证小数位:

export class PaymentBasicData {
    /**
     * Transaction amount.
     */
    @Expose()
    @IsNotEmpty()
    @IsNumber({ maxDecimalPlaces: 2 })
    @Min(0.01)
    @Max(999999999999999999.99)
    public amount: number;
}
Run Code Online (Sandbox Code Playgroud)

我应该number用点前 18 个数字和点后 2 个数字来验证 a 。它应该是什么样子?

typescript class-validator

5
推荐指数
0
解决办法
7237
查看次数

javascript/打字稿 | 类验证器 | 自定义验证装饰器| 覆盖“validator”方法中的“validationOptions”

考虑自定义验证装饰器部分中提供的示例:

// Decorator definition


import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function IsLongerThan(property: string, validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'isLongerThan',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [relatedPropertyName] = args.constraints;
          const relatedValue = (args.object as any)[relatedPropertyName];
          return typeof value === 'string' && typeof relatedValue === 'string' && value.length > relatedValue.length; // you can return a Promise<boolean> here as well, if you …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript class-validator

5
推荐指数
1
解决办法
3669
查看次数

是否可以使用类验证器验证 2 个参数之一是否存在?

将类验证器与 NestJS 一起使用,我想验证用户是否提供了一个或propertyA一个propertyB,但他们不需要同时提供两者。

目前,我正在做类似的事情:

export class TestDto {
  @ValidateIf(obj => !obj.propertyB)
  @IsString()
  @IsNotEmpty()
  propertyA

  @ValidateIf(obj => !obj.propertyA)
  @IsString()
  @IsNotEmpty()
  propertyB
}
Run Code Online (Sandbox Code Playgroud)

如果他们没有提供任何参数,则会出现多个错误,指出propertyApropertyB是必需的并且应该是字符串等。

如果他们不提供这两个属性,我只想要一个错误,例如:“您必须提供 propertyA 或 propertyB。”

这可以使用 NestJS/class-validator 来完成吗?

javascript validation typescript class-validator nestjs

5
推荐指数
1
解决办法
6952
查看次数

带有自定义错误消息的类验证器关系验证

所以我正在构建一个 API,用户在请求正文中向我们提供,type可以是valuetypeCNIC, EMAIL, MOBILE

现在基于type我必须验证该值,例如是否EMAIL有效或是否MOBILE有效等。

正如我们所看到的,该value字段依赖于type验证它的字段。

我需要一种方法来使用class-validator validationPipe.

typescript class-validator nestjs

5
推荐指数
1
解决办法
7797
查看次数

如何使用类验证器验证日期数组?

我想验证发布请求正文中的日期数组:

{
    "meals": [...],
    "dates": [
        "2022-03-06T11:00:00.000Z",
        "2022-03-07T11:00:00.000Z"
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是我的 dto 课程:

export class CopyMealsPlanDto {
...// Another array

  @IsArray()
  @ValidateNested({ each: true })
  @IsDate()
  @Type(() => Date)
  dates: Date[];
}

Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

{
    "statusCode": 400,
    "message": [
        "dates must be a Date instance"
    ],
    "error": "Bad Request"
}
Run Code Online (Sandbox Code Playgroud)

api class-validator nestjs

5
推荐指数
2
解决办法
2万
查看次数