# Pipes & Validation — NestJS: Building Scalable Node.js APIs

Source: https://www.skillbyai.com/en/nestjs/nestjs-pipes-validation

> Validate and transform input with ValidationPipe, class-validator DTOs and custom pipes before handlers run.

## Built-in pipes & class-validator

Use `ValidationPipe` with `class-validator` decorators to automatically validate DTOs.

```typescript
// dto
import { IsString, IsEmail, IsNumber } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsEmail()
  email: string;

  @IsNumber()
  age: number;
}

// main.ts
app.useGlobalPipes(new ValidationPipe());
```

## Custom pipes

Implement `PipeTransform` to create a custom pipe for unique validation or transformation logic.

```typescript
@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
  transform(value: string): number {
    const num = parseInt(value, 10);
    if (isNaN(num)) throw new BadRequestException();
    return num;
  }
}

@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { ... }
```

## ParseIntPipe on a route param

Route params arrive as strings. `ParseIntPipe` converts to a number or throws 400.

- `GET /users/7` gives `id = 7` (a number).
- `GET /users/abc` returns `400 Bad Request` automatically.

```ts
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return { id, type: typeof id };
  }
}
```

Output:

```
{"id":7,"type":"number"}
```

Quick check

**Quiz:** `ValidationPipe` does not reject unknown properties by default. Which option strips them?

- [x] `whitelist: true`
- [ ] `transform: false`
- [ ] `skipMissingProperties: true`

*Answer:* `whitelist: true`. `whitelist: true` removes properties without validation decorators; `forbidNonWhitelisted` makes them an error.
