# Validation

## Validation

유효성 검사는 모든 웹 응용 프로그램에 필수적인 기능입니다. 들어오는 요청을 자동으로 확인하기 위해 내장된 `ValidationPipe`가 사용하는 [class-validator](https://github.com/typestack/class-validator) 패키지를 활용합니다. `ValidationPipe`는 다양한 강력한 유효성 검사 규칙을 사용하여 들어오는 클라이언트 페이로드를 확인하는 편리한 방법을 제공합니다.

## Overview

[파이프](https://app.gitbook.com/pipes) 장에서 우리는 단순화된 검증 파이프를 만드는 과정을 거쳤습니다. 우리가 수행하는 작업을 더 잘 이해하려면 이 기사를 읽는 것이 좋습니다. 여기서는 주로 실제 사용 사례에 중점을 둘 것입니다.

## Auto-validation

이 자습서를 위해 `ValidationPipe`를 전체 응용 프로그램에 바인딩하므로 모든 엔드포인트가 잘못된 데이터로부터 자동으로 보호됩니다.

```typescript
async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();
```

파이프를 테스트하기 위해 기본 엔드포인트를 만들어 봅시다.

```typescript
@Post()
create(@Body() createUserDto: CreateUserDto) {
  return 'This action adds a new user';
}
```

그런 다음 CreateUserDto에 몇 가지 유효성 검사 규칙을 추가하십시오.

```typescript
import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}
```

이제 누군가가 유효하지 않은 `email`로 엔드 포인트를 요청하면 애플리케이션은 `400 Bad Request`코드와 다음 응답 본문으로 응답합니다.

```javascript
{
  "statusCode": 400,
  "error": "Bad Request",
  "message": [
    {
      "target": {},
      "property": "email",
      "children": [],
      "constraints": {
        "isEmail": "email must be an email"
      }
    }
  ]
}
```

분명히 응답 본문은 `ValidationPipe`의 유일한 사용 사례가 아닙니다. 엔드 포인트 경로에서 `:id`를 받고 싶다고 상상해 보십시오. 그래도 숫자만 유효합니다. 이것은 매우 간단합니다.

```typescript
@Get(':id')
findOne(@Param() params: FindOneParams) {
  return 'This action returns a user';
}
```

그리고 `FindOneParams`는 다음과 같습니다.

```typescript
import { IsNumberString } from 'class-validator';

export class FindOneParams {
  @IsNumberString()
  id: number;
}
```

## Disable detailed errors

오류 메시지는 네트워크를 통해 전송된 데이터의 문제점을 이해하는 데 많은 도움이 됩니다. 그러나 일부 프로덕션 환경에서는 자세한 오류를 사용하지 않을 수 있습니다.

```typescript
app.useGlobalPipes(
  new ValidationPipe({
    disableErrorMessages: true,
  }),
);
```

이제 최종 사용자에게 오류 메시지가 채워지지 않습니다.

## Stripping properties

종종 미리 정의 된 (허용 된) 속성만 전달하고 싶습니다. 예를 들어, 우리가 `email`과 `password` 속성을 기대한다면 누군가가 `age`를 보낼 때 이 속성은 제거되어 DTO에서 사용할 수 없게 됩니다. 이러한 동작을 가능하게하려면`whitelist`를 `true`로 설정하십시오.

```typescript
app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,
  }),
);
```

이 설정은 화이트리스트에 포함되지 않은 (데코레이터없이) 속성의 자동 제거를 활성화합니다. 그러나 요청 처리를 완전히 중지하고 사용자에게 오류 응답을 반환하려면 `whitelist`와 함께 `forbidNonWhitelisted`를 사용하십시오.

## Auto payload transforming

`ValidationPipe`는 페이로드를 해당 DTO 클래스로 자동 변환하지 않습니다. 컨트롤러 메소드에서 `createUserDto` 또는 `findOneParams`를 살펴보면 실제 클래스가 아니라는 것을 알 수 있습니다. 자동 변환을 활성화하려면`transform`을`true`로 설정하십시오.

```typescript
app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);
```

## Websockets & Microservices

이러한 모든 지침은 사용중인 전송 방법에 관계없이 WebSocket과 마이크로 서비스를 모두 고려했습니다.

## Learn more

사용자 지정 유효성 검사기, 오류 메시지 및 사용 가능한 데코레이터에 대한 자세한 내용을 보려면 이 [페이지](https://github.com/typestack/class-validator)를 방문하십시오.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jakekwak.gitbook.io/nestjs/techniques/validation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
