我有一个 NestJs dto,看起来像这样
import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator';
import { AppService } from './app.service';
const restrictedNames = ['Name Inc', 'Acme Inc'];
class DTO {
@IsNotEmpty()
name: string;
@IsEmail()
email: string;
@IsNotEmpty()
@IsNotIn(restrictedNames)
orgName: string;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用一个异常过滤器,它返回错误,并提供有关验证失败的内容和哪个字段的清晰详细信息。
app.useGlobalPipes(
new ValidationPipe({
exceptionFactory: (validationErrors: ValidationError[] = []) => {
console.log(validationErrors);
return new BadRequestException({
statusCode: HttpStatus.BAD_REQUEST,
message: validationErrors.reduce((acc, error) => {
acc[error.property] = Object.keys(error.constraints).map(
(failed) => ({
failedValidation: failed,
message: error.constraints[failed],
}),
);
return acc;
}, {}),
error: 'validation',
});
}, …
Run Code Online (Sandbox Code Playgroud) 让我们在 NestJS 项目中使用这个控制器:
@Post('resetpassword')
@HttpCode(200)
async requestPasswordReset(
@Body() body: RequestPasswordResetDTO,
): Promise<boolean> {
try {
return await this.authService.requestPasswordReset(body);
} catch (e) {
if (e instanceof EntityNotFoundError) {
// Throw same exception format as class-validator throwing (ValidationError)
} else throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
Dto定义:
export class RequestPasswordResetDTO {
@IsNotEmpty()
@IsEmail()
public email!: string;
}
Run Code Online (Sandbox Code Playgroud)
我想ValidationError
在this.authService.requestPasswordReset(body);
抛出EntityNotFoundError
异常时抛出格式错误(属性、值、约束等)。
如何手动创建此错误?当 DTO 验证class-validator
失败时才会抛出这些错误。这些可以只是静态验证,而不是异步数据库验证。
所以最终的 API 响应格式应该是例如:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"email": …
Run Code Online (Sandbox Code Playgroud) 我有这样的 anum:
export enum UserRole {
USER,
ADMIN,
BLOGGER
}
Run Code Online (Sandbox Code Playgroud)
并像这样 create.user.dto
import { IsEmail, IsEnum, IsNotEmpty, IsOptional } from 'class-validator';
import { UserRole } from './user.entity';
export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
firstName: string;
@IsNotEmpty()
lastName: string;
@IsOptional()
username: string;
@IsOptional()
@IsEnum(UserRole)
role: UserRole;
@IsNotEmpty()
password: string;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我只发布角色大写 ('ADMIN','USER') 或 'BLOGGER',角色验证不会失败。
如何使类验证器不区分大小写?我的意思是,也验证“admin”“aDmIn”为真。
我正在使用nestjs/graphql
, 并且为 graphql 突变创建了一个 dto,其中我使用了@IsString()
和等类验证器选项@IsBoolean()
。为此我安装了class-validator
和class-transformer
. 但是当我进行突变时,它给了我一个闻所未闻的错误。我用谷歌搜索了它,但没有结果。\n错误是这样的:
[Nest] 5872 - 2021. 11. 21. \xec\x98\xa4\xed\x9b\x84 7:56:09 ERROR [ExceptionsHandler] classTransformer.plainToClass is not a function\nTypeError: classTransformer.plainToClass is not a function\n at ValidationPipe.transform (/home/inust33/ubereats-backend/node_modules/@nestjs/common/pipes/validation.pipe.js:51:39)\n at /home/inust33/ubereats-backend/node_modules/@nestjs/core/pipes/pipes-consumer.js:16:33\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n
Run Code Online (Sandbox Code Playgroud)\n在操场上,它向我显示如下:\n graphql 操场错误
\n我的 dto 看起来像这样:
\n@ArgsType()\nexport class createRestaurantDto {\n @Field((type) => String)\n @IsString()\n @Length(5, 10)\n name: string;\n\n @Field((type) => Boolean)\n @IsBoolean()\n isVegan: boolean;\n\n @Field((type) => String)\n @IsString()\n address: string;\n\n @Field((type) => …
Run Code Online (Sandbox Code Playgroud) 我在 NestJS 中有一个用户的 DTO 类。我正在使用类验证器包进行许多验证,以强制执行我的逻辑。如果 DTO 定义中不存在某个字段,我想忽略它,甚至抛出错误。这就是我尝试使用“excludeExtraneousValues”标志的原因。当我使用它时,它会忽略所有字段,甚至是 DTO 中定义的字段。
import { ApiPropertyOptional } from '@nestjs/swagger';
import {
IsDefined,
IsEmail,
IsOptional,
IsPhoneNumber,
MaxLength,
ValidateIf,
} from 'class-validator';
export default class UserDTO {
@ApiPropertyOptional()
@MaxLength(254)
@IsEmail()
@IsDefined()
@ValidateIf((object) => object.email || !object.phone_number)
email?: string;
@ApiPropertyOptional()
@MaxLength(15)
@IsPhoneNumber()
@IsDefined()
@ValidateIf((object) => object.phone_number || !object.email)
phone_number?: string;
@ApiPropertyOptional()
@IsOptional()
@MaxLength(40)
name?: string;
}
Run Code Online (Sandbox Code Playgroud)
正如我提到的,我正在使用 NestJS。这是 ValidationPipe 定义:
app.useGlobalPipes(
new ValidationPipe({
transform: true,
stopAtFirstError: true,
transformOptions: { excludeExtraneousValues: true },
}),
);
Run Code Online (Sandbox Code Playgroud)
添加“excludeExtraneousValues”标志后,我无法发送任何值,即使是定义的值。
这是一个错误还是我错过了什么?
我正在尝试使用类验证器来验证传入的数据。数据由对象数组组成。每个对象都应该经过验证。
我面临的问题是,当所有内容都正确输入时,我不断收到错误。似乎正在检查父类及其子类的属性,因此whitelistValidation
子类的每个属性都会抛出错误。
这是正在生成的错误:
[
{
"target":{
"drainPoints":[
{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
}
]
},
"value":[
{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
}
],
"property":"drainPoints",
"children":[
{
"target":[
{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
}
],
"value":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"property":"0",
"children":[
{
"target":{
"drainPointType":"roundsurface",
"flowType":"normal",
"flowCoefficient":0.5,
"point":{
"x":0,
"y":0
}
},
"value":"roundsurface",
"property":"drainPointType",
"constraints":{
"whitelistValidation":"property drainPointType should not exist"
}
},
{
"target":{
"drainPointType":"roundsurface",
"flowType":"normal", …
Run Code Online (Sandbox Code Playgroud) 我想在nest.js控制器中使用class-validator验证身体有效载荷。我的currency.dto.ts
文件是这样的:
import {
IsNotEmpty,
IsString,
ValidateNested,
IsNumber,
IsDefined,
} from 'class-validator';
class Data {
@IsNotEmpty()
@IsString()
type: string;
@IsNotEmpty()
@IsNumber()
id: number;
}
export class CurrencyDTO {
@ValidateNested({ each: true })
@IsDefined()
data: Data[];
}
Run Code Online (Sandbox Code Playgroud)
在我的nest.js控制器中,我像这样使用它。
@Post()
@UseGuards(new AuthTokenGuard())
@UsePipes(new ValidationPipe())
addNewCurrency(@Req() req, @Body() data: CurrencyDTO) {
console.log('data', data);
}
Run Code Online (Sandbox Code Playgroud)
我的验证管道类是这样的:
import {
PipeTransform,
Injectable,
ArgumentMetadata,
BadRequestException,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { validate, IsInstance } from 'class-validator';
import { plainToClass, Exclude } from 'class-transformer';
@Injectable()
export …
Run Code Online (Sandbox Code Playgroud)我正在尝试使用class-validator和NestJS验证嵌套对象。我已经尝试通过使用class-transform 的装饰器来跟踪此线程@Type
,但没有任何运气。这是我所拥有的:
DTO:
class PositionDto {
@IsNumber()
cost: number;
@IsNumber()
quantity: number;
}
export class FreeAgentsCreateEventDto {
@IsNumber()
eventId: number;
@IsEnum(FinderGamesSkillLevel)
skillLevel: FinderGamesSkillLevel;
@ValidateNested({ each: true })
@Type(() => PositionDto)
positions: PositionDto[];
}
Run Code Online (Sandbox Code Playgroud)
我也在使用内置的nestjs验证管道,这是我的引导程序:
async function bootstrap() {
const app = await NestFactory.create(ServerModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(config.PORT);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
对于其他属性,它工作正常,对象数组是唯一不起作用的数组。
我有一个猫鼬鉴别器模式,这意味着数据将根据属性之一而不同。
class Feature {
name: string
option: ColorFeature|SizeFeature
}
class ColorFeature {
kind: 'color'
color: string
}
class SizeFeature {
kind: 'size'
size: number
}
Run Code Online (Sandbox Code Playgroud)
验证Feature
类以使其只接受 2 种不同类型的正确方法是什么?
我在 NestJS 中使用类验证器来创建这样的验证:
export class LoginDTO {
@IsEmail()
@MinLength(4)
email: string;
@IsNotEmpty()
@MinLength(4)
password: string;
Run Code Online (Sandbox Code Playgroud)
}
它有效,但不像预期的那样。返回的对象如下所示:
{
"statusCode": 400,
"message": [
"email must be longer than or equal to 4 characters",
"email must be an email"
],
"error": "Bad Request"
Run Code Online (Sandbox Code Playgroud)
}
虽然我希望它包含这样的所有信息:
{
"statusCode": 400,
[{
target: /* post object */,
property: "title",
value: "Hello",
constraints: {
length: "$property must be longer than or equal to 10 characters"
}]
"error": "Bad Request"
}
Run Code Online (Sandbox Code Playgroud)
如何返回所有丢失的属性?
class-validator ×10
nestjs ×7
node.js ×6
typescript ×6
javascript ×3
dto ×2
enums ×1
express ×1
graphql ×1
validation ×1