[NestJS] class-validator

Younghwan Cha·2023년 8월 21일
0

Nest.js

목록 보기
20/27

express나 Nest.js 같은 웹 프레임워크에서는 요청의 JSON body를 검증하는데 사용할 수 있다. 다음과 같이 class-transformer와 class-validator를 이용해서 라우터나 컨트롤러에 도달하기 전에 요청의 JSON body를 클래스의 인스턴스로 변환한 뒤에 검증할 수 있다.

@IsNotEmpty(): 값이 비어있지 않은지 확인합니다.
@IsString(): 값이 문자열인지 확인합니다.

@IsNumber()
	값이 숫자인지 확인합니다. ( 3.14, 1, 10 )
@IsInt()
	값이 정수인지 확인합니다. ( 2, 4, 10 )

@IsBoolean(): 값이 불리언(참 또는 거짓)인지 확인합니다.
@IsArray(): 값이 배열인지 확인합니다.
@IsDate(): 값이 유효한 날짜인지 확인합니다.
@IsEmail(): 값이 유효한 이메일 주소인지 확인합니다.
@IsEnum(): 값이 주어진 열거형(Enum) 값 중 하나인지 확인합니다.
@Min(): 값이 주어진 최소 값보다 크거나 같은지 확인합니다.
@Max(): 값이 주어진 최대 값보다 작거나 같은지 확인합니다.
@Length(): 문자열의 길이가 주어진 범위 내에 있는지 확인합니다.
@IsOptional(): 값이 선택적인(optional)지 여부를 확인합니다.
@IsNotEmptyObject(): 객체가 비어있지 않은지 확인합니다.
@IsUUID(): 값이 UUID 형식인지 확인합니다.
@IsPhoneNumber(): 값이 유효한 전화번호 형식인지 확인합니다.
@IsUrl(): 값이 유효한 URL 형식인지 확인합니다.
    
    
@ValidateNested()
	중첩된 object 는 class instance 여야만 @ValidateNested 가 validation 을 할 수 있다.
@ValidateNested({ each: true })
	중첩된 object 가 배열일 경우, { each: true } 를 통해서 배열의 모든 element 가 validated 될 수 있도록 보장한다
@ValidatePromise()

@IsIn()
	const weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
	...
	@IsIn(weekdays)

@Matches
  // 알파벳으로 이루어져있는지 체크
  @Matches('^[a-zA-Z\\s]+$', undefined, { each: true })

@Contains
  // 'hello' 문자를 포함하고 있는 지 체크
  @Contains('hello', { each: true })

검증을 위한 다양한 validation option 들을 사용할 수 있다.
이들에 대해서 알아보자.

Stripping properties


  • whitelist
  • forbidNonWhitelisted

whitelist 의 경우 정의 되지 않은 property 를 제외하고 전달하고
forbidNonWhitelisted 는 정의 되지 않은 property 를 발견하면 에러를 던진다.

Our ValidationPipe can also filter out properties that should not be received by the method handler. In this case, we can whitelist the acceptable properties, and any property not included in the whitelist is automatically stripped from the resulting object. For example, if our handler expects email and password properties, but a request also includes an age property, this property can be automatically removed from the resulting DTO. To enable such behavior, set whitelist to true.

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

https://github.com/typestack/class-validator#validation-decorators

[class validator github] https://github.com/typestack/class-validator

profile
개발 기록

0개의 댓글