我有一组看起来像这样的对象
[{
name: 'some name'
catId: 2,
}, {
name: 'another name'
catId: 3,
}]
Run Code Online (Sandbox Code Playgroud)
如何使用类验证器进行验证,以便名称字段是必需的,并且每个对象的长度至少为 2 个字符?
谢谢
我想在对象构造函数中使用 validateSync,但无法将其与继承一起使用。
我有这样的事情:
import { IsNotEmpty, IsString, validateSync, validate } from 'class-validator';
class Animal {
@IsNotEmpty()
@IsString()
public name: string;
constructor(name: string) {
this.name = name;
this.validate() // this method calls validate of class Dog, since this is an instance of Dog
}
protected validate() {
const errors = validateSync(this);
if (errors.length > 0) {
console.log("Animal validation error: ", errors)
}
}
}
class Dog extends Animal {
@IsNotEmpty()
@IsString()
public breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed …Run Code Online (Sandbox Code Playgroud) 使用类验证器,验证管道我想根据需要标记一些字段。我尝试使用@IsNotEmpty方法。当输入为空时,它会抛出 400 错误。但如果输入也丢失,我需要抛出错误。
DTO:地址对象,包含字段地址 1 和地址 2。我希望地址 1 为必需,地址 2 为可选
import {IsString, IsInt, IsNotEmpty } from 'class-validator';
import {ApiModelProperty} from '@nestjs/swagger';
export class Address {
@ApiModelProperty({description: 'Address Line 1', required : true})
@IsString()
@IsNotEmpty()
required : true
address1: string;
@ApiModelProperty({description: 'Address Line 2', required :false})
@IsString()
address2?: string;
}
Run Code Online (Sandbox Code Playgroud)
// App.js: Application file where validation pipes are defined.
async function bootstrap() {
const expressServer = express();
const app = await NestFactory.create(AppModule, expressServer, {bodyParser: true});
app.use(bodyParser.json({limit: 6851000}));
app.useGlobalInterceptors(new …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用转换将 formData 请求从字符串转换为 json 对象,然后使用validationPipe(类验证器)进行验证,但我得到
Maximum call stack size exceeded
at cloneObject (E:\projectos\Gitlab\latineo\latineo-apirest\node_modules\mongoose\lib\utils.js:290:21)
at clone (E:\projectos\Gitlab\latineo\latineo-apirest\node_modules\mongoose\lib\utils.js:204:16)
Run Code Online (Sandbox Code Playgroud)
尝试调试后,我进入控制器 3 次,对象保存在数据库中,但没有验证,内部 TransformJSONToObject 9 次...
我的 main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ transform: true }));
app.use(helmet());
app.enableCors();
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 4000, // limit each IP to 100 requests per windowMs
}),
);
app.use(compression());
app.use('/upload', express.static(join(__dirname, '..', 'upload')));
const options = new DocumentBuilder()
.setTitle('XXX')
.setDescription('XXX')
.setVersion('1.0')
.addBearerAuth()
.build();
const …Run Code Online (Sandbox Code Playgroud) 我在 Nest js 中有以下类和此类验证器:
@ValidateIf(val => val !== '*')
@IsObject()
@IsNotEmptyObject()
queryParams: DbQuery | '*';
Run Code Online (Sandbox Code Playgroud)
如果我发送 '*' 它会返回
[ 'queryParams must be a non-empty object' ]
Run Code Online (Sandbox Code Playgroud) 我正在设置一个新的 NestJS 应用程序,我刚刚添加了 class-validator 以验证控制器输入,但它似乎被完全忽略了。这是 DTO:
import {IsString} from 'class-validator';
export class CreateCompanyDto {
@IsString()
name: string | undefined;
}
Run Code Online (Sandbox Code Playgroud)
这是控制器:
import {
Body,
Controller,
InternalServerErrorException,
Post,
Request,
UseGuards, ValidationPipe
} from '@nestjs/common';
import * as admin from 'firebase-admin';
import {User} from 'firebase';
import {AuthGuard} from '../auth/auth.guard';
import {CurrentUser} from '../auth/current-user.decorator';
import {CreateCompanyDto} from './dto/create-company.dto';
@Controller('vendor')
export class VendorController {
@Post()
@UseGuards(AuthGuard)
async create(@CurrentUser() user: User, @Request() req: any, @Body(new ValidationPipe({ transform: true })) company: CreateCompanyDto) {
console.log(JSON.stringify(company));
throw new …Run Code Online (Sandbox Code Playgroud) 我想用 NestJs、TypeORM 和类验证器创建一个 REST API。我的数据库实体有一个当前最大长度为 3000 的描述字段。使用 TypeORM,代码是
@Entity()
export class Location extends BaseEntity {
@Column({ length: 3000 })
public description: string;
}
Run Code Online (Sandbox Code Playgroud)
创建新实体时,我想使用类验证器验证该最大长度的传入请求。可能是
export class AddLocationDTO {
@IsString()
@MaxLength(3000)
public description: string;
}
Run Code Online (Sandbox Code Playgroud)
更新该描述字段时,我也必须检查其他 DTO 中的最大长度。我有一个服务类,其中包含 API 的所有配置字段。假设这个服务类也可以提供最大长度,有没有办法将变量传递给装饰器?
否则,当将长度从 3000 更改为 2000 时,我必须更改多个文件。
我有 NestJS API,它有一个用于修改资源的 PATCH 端点。我使用该class-validator库来验证有效负载。在 DTO 中,所有字段都通过@IsOptional()装饰器设置为可选。因此,如果我发送空负载,验证就会通过,然后更新操作就会出错。
我想知道是否有一种简单的方法可以像我一样将所有字段设置为可选,同时确保其中至少一个字段不为空,因此对象不为空。
谢谢!
我有一个 DTO,其中有一个字段,它是一个数字数组。这些 id 来自 API 查询参数。我正在使用 Class Transformer 将这些 id 转换为数字数组。但我只得到一个字符串数组。我的 DTO 课程如下。
export class EvseGetQueryDto {
...
...
@IsOptional()
@IsArray()
@IsNumber({}, {each: true})
@ApiProperty({ type: [Number] })
@Type(() => Number)
locations?: number[];
...
...
}
Run Code Online (Sandbox Code Playgroud)
我的控制器代码如下所示。
async GetAll(@Query() query: EvseGetQueryDto): Promise<EvseDto[]> {
return await this.evseService.GetAll(query);
}
Run Code Online (Sandbox Code Playgroud)
如果我像下面这样调用我的控制器,我仍然['1', '2']在我的位置字段中。
http://localhost:3000/evses?locations[]=1&locations[]=2
Run Code Online (Sandbox Code Playgroud)
任何人都可以指导我吗?
我将类验证器与 NestJS 结合使用,并尝试使用以下布局验证对象数组:
[
{gameId: 1, numbers: [1, 2, 3, 5, 6]},
{gameId: 2, numbers: [5, 6, 3, 5, 8]}
]
Run Code Online (Sandbox Code Playgroud)
我的解析器
createBet(@Args('createBetInput') createBetInput: CreateBetInput) {
return this.betsService.create(createBetInput);
}
Run Code Online (Sandbox Code Playgroud)
我的 createBetInput DTO
import { InputType, Field, Int } from '@nestjs/graphql';
import { IsArray, IsNumber } from 'class-validator';
@InputType()
export class CreateBetInput {
@IsNumber()
@Field(() => Int)
gameId: number;
@Field(() => [Int])
@IsArray()
numbers: number[];
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一些解决方案,但没有成功,老实说,我不知道该怎么做。
如何修改 DTO 以获得必要的验证?
class-validator ×10
nestjs ×8
typescript ×5
node.js ×3
javascript ×2
arrays ×1
graphql ×1
transform ×1
validation ×1