PracticeEveryday
Joi 본문
Joi
사용자가 입력한 데이터가 유효한지 검사하는 유효성 검사 라이브러리!
const loginValidation = async (req, res, next) => {
const body = req.body;
// validate할 schema 정의
const userSchema = joi.object({
email: joi
.string() // 들어오는 값은 문자열
.email(), // 이메일 패턴
password: joi
.string() // 들어오는 값은 문자열
.min(4) // 최소 4자리 이상
.required(), // 빈값이 올수 없음!
});
try {
await userSchema.validateAsync(body);
} catch (error) {
res.status(400).json({ code: 400, message: error.message });
}
};
+
위에서 지정한 검사 그룹인 userSchema를 validateAsync를 사용하여 검사 시, 전체 구문을 try~catch 구문으로 묶어 비동기적으로 처리할 수 있다. validation에 실패한 경우 catch 문에서 에러를 발생시킨다.
다른 좋은 예시들
// { number, string }
Joi.object({
number: Joi.number()
string: Joi.string()
})
// Array<number>
Joi.array().items(Joi.number())
// Array<number> number > 10 and number < 20
Joi.array().items(Joi.number().min(10).max(20))
// a < b
Joi.object({
a: Joi.number().max(Joi.ref('b'))
b: Joi.number()
})
// ['a', 'a'] (x) 즉, 중복값 허용 안됨
Joi.array().items(Joi.string()).unique()
// 다른 배열에 있는 수와 같으면 안됨
const a = [1,2,3,4]
const b = [1,2]
Joi.object({
a: Joi.array().items(Joi.number().invalid(...b)),
b: Joi.array().items(Joi.number())
})
/* 1,2 가 중복되므로 에러 발생 */
[출처] Node : Joi 활용하기|작성자 ondaa
const userId_pattern = /^[a-z|A-Z|0-9]+$/; // userId는 알파벳 대소문자 (a~z, A~Z), 숫자(0~9)로 구성
const nickname_pattern = /^[ㄱ-ㅎ|가-힣|a-z|A-Z|0-9]+$/; // 닉네임은 한글, 알파벳 대소문자 (a~z, A~Z), 숫자(0~9)로 구성
const postUserSchema = Joi.object({
userId: Joi.string()
.min(3)
.pattern(new RegExp(userId_pattern))
.required(),
password: Joi.string().min(4).required(),
nickname: Joi.string()
.min(2)
.pattern(new RegExp(nickname_pattern))
.required(),
});
https://velog.io/@sinclebear/Joi-Validator
'정리 > Question' 카테고리의 다른 글
JavaScript// 싱글 스레드 (0) | 2022.05.15 |
---|---|
얕은 복사 vs 깊은 복사 + 함정 (0) | 2022.05.13 |
자료구조? 알고리즘? 추상 자료형? (0) | 2022.05.09 |
Call by value vs Call by reference (0) | 2022.05.04 |
prototype vs __proto__ (0) | 2022.05.04 |
Comments