例如,对于数据库行,我们可能需要可为空的属性,并且这些属性不得未定义:
class DbRow {
@IsNumber()
id!: number;
@IsNumber()
numNullable!: number | null;
}
Run Code Online (Sandbox Code Playgroud)
所以numNullable
可以是数字或null
- 但绝不能是undefined
。
我们如何在类验证器中表达这一点?
@Optional()
不起作用,因为这也将允许undefined
我正在将类验证器包与 NestJS 一起使用,并且我希望验证一组对象,这些对象需要恰好具有 2 个具有相同布局的对象:
到目前为止,我有:
import { IsString, IsNumber } from 'class-validator';
export class AuthParam {
@IsNumber()
id: number;
@IsString()
type: string;
@IsString()
value: string;
}
Run Code Online (Sandbox Code Playgroud)
和
import { IsArray, ValidateNested } from 'class-validator';
import { AuthParam } from './authParam.model';
export class SignIn {
@IsArray()
@ValidateNested({ each: true })
authParameters: AuthParam[];
}
Run Code Online (Sandbox Code Playgroud)
每个@kamilg 响应(我能够强制执行 2 个元素):
import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';
import { AuthParam } from './authParam.model';
export class SignInModel {
@IsArray()
@ValidateNested({ each: true …
Run Code Online (Sandbox Code Playgroud) 今天,我试图弄清楚如何在应用程序的后端 (NestJS) 中验证注册表单。我只是想知道是否存在一种验证password
和passwordConfirm
匹配的方法,使用class-validator
包来构建自定义验证器或利用提供的验证器。我在考虑类验证器,而不是字段验证器。
// Maybe validator here
export class SignUpDto {
@IsString()
@MinLength(4)
@MaxLength(20)
username: string;
@IsString()
@MinLength(4)
@MaxLength(20)
@Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {message: 'password too weak'})
password: string;
@IsString()
@MinLength(4)
@MaxLength(20)
passwordConfirm: string;
}
Run Code Online (Sandbox Code Playgroud)
你有什么建议?
我有这种类型:
export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';
Run Code Online (Sandbox Code Playgroud)
我可以使用哪个类验证器装饰器来验证属性是否具有这些值之一?
import { IsEmail, IsString, Contains } from "class-validator";
export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';
export class AddBranchOperatorRequest extends User {
@IsEmail()
email: string;
@Contains(BranchOperatorRole )
role: BranchOperatorRole;
}
Run Code Online (Sandbox Code Playgroud) 我使用内置的 NestJS ValidationPipe 以及类验证器和类转换器来验证和清理入站 JSON 正文有效负载。我面临的一种情况是入站 JSON 对象中混合使用大小写属性名称。我想在新的 TypeScript NestJS API 中纠正这些属性并将其映射到标准的驼峰式模型,这样我就不会将遗留系统中不匹配的模式耦合到我们的新 API 和新标准,本质上是使用 @Transform DTO 作为应用程序其余部分的隔离机制。例如,入站 JSON 对象的属性:
"propertyone",
"PROPERTYTWO",
"PropertyThree"
Run Code Online (Sandbox Code Playgroud)
应该映射到
"propertyOne",
"propertyTwo",
"propertyThree"
Run Code Online (Sandbox Code Playgroud)
我想使用 @Transform 来完成此任务,但我认为我的方法不正确。我想知道是否需要编写自定义 ValidationPipe。这是我目前的方法。
控制器:
"propertyone",
"PROPERTYTWO",
"PropertyThree"
Run Code Online (Sandbox Code Playgroud)
测试我模型:
"propertyOne",
"propertyTwo",
"propertyThree"
Run Code Online (Sandbox Code Playgroud)
测试我请求Dto:
import { Body, Controller, Post, UsePipes, ValidationPipe } from '@nestjs/common';
import { TestMeRequestDto } from './testmerequest.dto';
@Controller('test')
export class TestController {
constructor() {}
@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async get(@Body() testMeRequestDto: TestMeRequestDto): Promise<TestMeResponseDto> {
const response = do something useful …
Run Code Online (Sandbox Code Playgroud) import { isEmail, isEmpty, isPhoneNumber, Length } from "class-validator"
import { Field, InputType } from "type-graphql";
@InputType()
export class RegisterInput {
@Field()
@Length(2, 15, { message: "Username Must Be At Least 2 characters" })
username?: string;
@Field()
@isEmail()
email?: string;
@Field()
@Length(1, 20)
@isPhoneNumber()
phoneNumber?: string;
@isEmpty()
password?: string
}
Run Code Online (Sandbox Code Playgroud)
问题是 @isEmail() 和 @isPhoneNumber() 和 @isEmpty() 抛出相同的错误:
Unable to resolve signature of property decorator when called as an expression.
This expression is not callable.
Type 'Boolean' has no call signatures.ts(1240) …
Run Code Online (Sandbox Code Playgroud) 创建新用户将忽略来自 create-user.dto.ts
但是,当我更新用户时,它会添加不需要的字段,如下所示:
// update-user.dto.ts
import { IsEmail } from 'class-validator';
import { Address } from '../model/address';
export class UpdateUserDto {
firstName: string;
lastName: string;
@IsEmail(undefined, { message: 'Not a valid e-mail' })
email: string;
username: string;
password: string;
addresses: Address[];
}
Run Code Online (Sandbox Code Playgroud)
这是来自用户服务的更新操作
// user.service.ts
async update(data: UpdateUserDto) {
try {
this.logger.log(data);
const id = '5c6dd9852d4f441638c2df86';
const user = await this.userRepository.update(id, data);
return { message: 'Updated your information' };
} catch (error) {
this.logger.log(error);
throw new HttpException('', HttpStatus.INTERNAL_SERVER_ERROR);
}
} …
Run Code Online (Sandbox Code Playgroud) 我想对请求有效负载应用验证,例如有字符串类型的字段名称。但名称不是必填字段,但如果存在,则必须执行@IsNotEmpty()
我试过这样的事情
@IsNotEmpty() name?: string
//它不考虑?
可选约束
如何转换数据库实体User
:
class User {
public firstName: string;
public lastName: string;
public phone?: string;
public email: string;
public status: EUserState;
public tokens: Token[];
public password: string;
}
Run Code Online (Sandbox Code Playgroud)
进入 DTO 实体GetUserDTO
:
class GetUserDTO {
public id: number;
public firstName: string;
public lastName: string;
public phone?: string;
public email: string;
}
Run Code Online (Sandbox Code Playgroud)
在打字稿中?我正在使用@nestjs
,class-validator
和class-transformer
包,但我没有找到任何方法来使用它们来实现这一目标。
有人可能会说,拥有 DTO 对此毫无意义,但我们在服务器和客户端之间共享 DTO 以维护 API 结构。
有任何想法吗?
我有 TypeScript NestJS 项目。
我需要验证传入 API 的 DTO。它可以被描述为“创建项目”,其中我们有建筑类型(房屋、公寓、花园),并且根据该类型我们需要定义:
房屋类型示例:
{
type: HOUSE,
floors: [
{
name: "1st floor",
rooms: [
{
name: "bedroom"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
平面类型示例:
{
type: FLAT,
rooms: [
{
name: "bedroom"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我过去在 的帮助下完成了这件事AJV
,但现在当我们迁移到 NestJS 时,我们开始使用class-validator
.
我的问题是,我是否可以在 中创建这些高级条件(例如,当类型为 FLAT 时,则仅期望 ROOMS,而不是 FLOORS)class-validator
?
class-validator ×10
nestjs ×7
typescript ×6
validation ×3
node.js ×2
ajv ×1
arrays ×1
dto ×1
graphql ×1
javascript ×1
mongodb ×1
typegraphql ×1
typeorm ×1