Nestjs is a Node.js framework for building efficient server-side apps. It uses TypeScript and integrates class-validator for data validation. To validate DTOs, which define data shapes, you add decorators like @IsEmail()
or @IsNotEmpty()
to class properties. For instance, a CreateUserDto class might look like:
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
@IsString()
password: string;
@IsNotEmpty()
@IsString()
name: string;
}
To globally apply validation, use the ValidationPipe
in your main.ts
:
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
For testing, use class-validator's functions like plainToClass
and validateSync
. A Jest unit test example:
import { plainToClass } from 'class-transformer';
import { validateSync } from 'class-validator';
import { CreateUserDto } from './create-user.dto';
describe('CreateUserDto', () => {
it('should be valid with valid properties', () => {
const createUserDto = plainToClass(CreateUserDto, {
email: 'admin@gmail.com',
password: 'xxxxxxxx',
name: 'Admin',
});
const errors = validateSync(createUserDto);
expect(errors).toHaveLength(0);
});
it('should be invalid with invalid properties', () => {
const createUserDto = plainToClass(CreateUserDto, {
email: 'admin@gmail.com',
password: 'xxxxxxxx',
name: null,
});
const errors = validateSync(createUserDto);
expect(errors).toHaveLength(1);
// Check error details...
});
});
Nestjs and class-validator simplify building and testing apps by using decorators to validate data. For more info, see the official Nestjs and class-validator documentation.
Top comments (0)