
Research
/Security News
Mini Shai-Hulud Campaign Hits Red Hat Cloud Services npm Packages
A mini Shai-Hulud campaign compromised Red Hat Cloud Services npm packages to steal developer and CI/CD secrets during installation.
@hestjs/validation
Advanced tools
HestJS 验证模块,基于 TypeBox 提供强类型验证功能。
npm install @hestjs/validation
# 或者
yarn add @hestjs/validation
# 或者
pnpm add @hestjs/validation
import { IsString, IsNumber, IsEmail, IsOptional } from '@hestjs/validation';
class CreateUserDto {
@IsString()
name: string;
@IsEmail()
email: string;
@IsNumber()
@IsOptional()
age?: number;
}
// 在控制器中使用
import { Body, Controller, Post } from '@hestjs/core';
@Controller('/users')
export class UserController {
@Post()
async createUser(@Body() createUserDto: CreateUserDto) {
// createUserDto 已经被自动验证
return { message: 'User created', user: createUserDto };
}
}
import { IsCustom, ValidationUtils } from '@hestjs/validation';
class ProductDto {
@IsString()
name: string;
@IsCustom((value) => value > 0, '价格必须大于0')
price: number;
}
import { ValidationUtils } from '@hestjs/validation';
// 验证对象
try {
const validatedUser = await ValidationUtils.validateObject(CreateUserDto, userData);
console.log('验证成功:', validatedUser);
} catch (error) {
console.log('验证失败:', error.message);
}
// 检查是否有效
const isValid = await ValidationUtils.isValid(CreateUserDto, userData);
// 获取验证错误
const errors = await ValidationUtils.getValidationErrors(CreateUserDto, userData);
// 批量验证
const { valid, errors: batchErrors } = await ValidationUtils.validateBatch(
CreateUserDto,
[userData1, userData2, userData3]
);
// 部分验证
const partialUser = await ValidationUtils.validatePartial(CreateUserDto, {
name: 'John' // 只验证提供的字段
});
@IsString() - 字符串验证@IsNumber() - 数字验证@IsBoolean() - 布尔值验证@IsArray() - 数组验证@IsObject() - 对象验证@IsEmail() - 邮箱格式验证@IsUrl() - URL 格式验证@IsUuid() - UUID 格式验证@MinLength(min) - 最小长度@MaxLength(max) - 最大长度@Matches(pattern) - 正则表达式匹配@Min(min) - 最小值@Max(max) - 最大值@IsPositive() - 正数@IsNegative() - 负数@IsInt() - 整数@IsDate() - 日期验证@IsDateString() - 日期字符串验证@IsOptional() - 可选字段@IsEnum(enumObject) - 枚举验证@IsCustom(validator, message) - 自定义验证class AddressDto {
@IsString()
street: string;
@IsString()
city: string;
@IsString()
@Matches(/^\d{5}$/)
zipCode: string;
}
class UserDto {
@IsString()
name: string;
@IsEmail()
email: string;
@ValidateNested()
@Type(() => AddressDto)
address: AddressDto;
}
class CreateUsersDto {
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateUserDto)
users: CreateUserDto[];
}
class ConditionalDto {
@IsString()
type: 'email' | 'phone';
@IsOptional()
@IsEmail()
@ValidateIf(o => o.type === 'email')
email?: string;
@IsOptional()
@IsPhoneNumber()
@ValidateIf(o => o.type === 'phone')
phone?: string;
}
import { ValidationModule } from '@hestjs/validation';
@Module({
imports: [
ValidationModule.forRoot({
whitelist: true, // 移除未装饰的属性
forbidNonWhitelisted: true, // 禁止非白名单属性
transform: true, // 自动类型转换
disableErrorMessages: false, // 禁用错误消息
dismissDefaultMessages: false, // 忽略默认消息
validationError: { target: false }, // 错误对象配置
}),
],
})
export class AppModule {}
import { ValidationPipe } from '@hestjs/validation';
// 在控制器方法中使用
@Post()
@UsePipes(new ValidationPipe({
transform: true,
whitelist: true,
}))
async createUser(@Body() createUserDto: CreateUserDto) {
return createUserDto;
}
验证错误会抛出 ValidationException,包含详细的错误信息:
try {
await ValidationUtils.validateObject(CreateUserDto, invalidData);
} catch (error) {
if (error instanceof ValidationException) {
console.log('验证错误:', error.getMessages());
console.log('错误详情:', error.getErrors());
}
}
完全支持 TypeScript,提供类型安全的验证:
// 自动类型推断
const user: CreateUserDto = await ValidationUtils.validateObject(CreateUserDto, data);
// 生成 TypeBox Schema
const schema = ValidationUtils.generateSchema(CreateUserDto);
import { Body, Controller, Post } from '@hestjs/core';
import { UseValidation } from '@hestjs/validation';
@Controller('/api')
@UseValidation() // 启用自动验证
export class ApiController {
@Post('/users')
async createUser(@Body() userData: CreateUserDto) {
// userData 已自动验证
return userData;
}
}
import { UseInterceptors } from '@hestjs/core';
import { ValidationInterceptor } from '@hestjs/validation';
@Controller('/api')
@UseInterceptors(ValidationInterceptor)
export class ApiController {
// ...
}
MIT
欢迎提交 Issue 和 Pull Request!
FAQs
HestJS Validation Module with TypeBox
We found that @hestjs/validation demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Research
/Security News
A mini Shai-Hulud campaign compromised Red Hat Cloud Services npm packages to steal developer and CI/CD secrets during installation.

Research
/Security News
The North Korean malware loader hides in a Packagist-listed package and its GitHub branch to fetch and execute remote code in a likely Contagious Interview-style lure.

Security News
The Rust project is moving toward formal rules on LLM use in contributions after months of internal debate over maintainer burden, code quality, and contributor experience.