validator
서버에서 유효성 검사를 해야하기 때문에 사용할 수 있는 유효성 검증 모듈
express-validator
class-validator 등 사용할 수 있다.
https://www.npmjs.com/package/class-validator?activeTab=readme
class-validator
class-validator
Decorator-based property validation for classes.. Latest version: 0.14.0, last published: 9 months ago. Start using class-validator in your project by running `npm i class-validator`. There are 4837 other projects in the npm registry using class-validator.
www.npmjs.com
회원가입 Response 유효성 검증
- npm 설치
npm install class-validator --save
- 대표적인 유효성 검증 decorators
Contains
: 포함 여부 검증IsInt
: 정수 검증Length
: 길이 검증IsEmail
: 이메일 검증IsFQDN
: 전체 도메인 이름 검증IsDate
: 날짜 형식 검증Min
: 최소값 검증Max
: 최대값 검증
...
그 외 다양한 유효성 검증은 공식문서에서 확인할 수 있다.
- 구현 예시
회원가입할 때 이메일, 비밀번호 등 입력 조건을 지정하고싶다.
export class JoinRequestDto {
@IsNotEmpty()
@IsEmail({}, { message: 'Invalid email format' })
@MaxLength(100, { message: 'Email should not exceed 100 characters' })
email: string;
@IsNotEmpty({ message: 'Password should not be empty' })
@Length(8, 30, { message: 'Password must be between 8 and 30 characters' })
@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,}$/, {
message: 'Password must contain at least 1 special, 1 upper, 1 lower character',
})
password: string;
@IsNotEmpty({ message: 'Name should not be empty' })
@IsString({ message: 'Name should be a string' })
@Length(3, 30, { message: 'Name must be between 3 and 30 characters' })
name: string;
@IsEnum(RoleEnum)
role: RoleType;
}
회원가입 user 정보를 담는 클래스에 class-validator를 적용하였다.
@IsEmail({}, { message: 'Invalid email format' })
message는 유효성 검증이 실패했을때 (이메일 형식이 아닐때) 보내주는 메세지이다. 에러 메세지로 활동할 수 있다.
@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,}$/, {
message: 'Password must contain at least 1 special, 1 upper, 1 lower character',
})
password를 정규표현식을 사용해서 대소문자,특수문자를 포함하도록 했다.
다양한 validator로 유효성을 적용하고,
이 적용시킨것을 확인하기 위한 코드가 필요하다
- validate 구현 예시
validator에 값을 적용시킨 인스턴스를validate()
를 통해 확인한다.
위 dto에 들어온 값이 담긴 인스턴스를 적용 해 보았다. class-transformer의 plainToInstance 활용하였다.
const validator = plainToInstance(JoinRequestDto, req.body);
const validationErrors = await validate(validator);
if (validationErrors.length > 0) {
throw new ValidationError('Validation Error');
}
결과값을 에러를 반환하는데, 에러가 없으면 통과된것이고 에러가 있으면 에러처리하면 된다.
나는 validator가 어떤곳에서 어떤 에러가 낫는지 깔끔하게 보기위해 따로 에러메세지 처리를 했는데 여기선 생략한다.