ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2024-06-17 TIL ( Joi 사용방법 )
    카테고리 없음 2024. 6. 18. 14:12

    Joi

    사용자가 입력한 데이터가 유효한지 검사하는 유효성 검사 라이브러리

     

     

    Install 방법 

    yarn add Joi
    //yarn
    
    npx install Joi
    //npx

     

    import 

    import Joi from 'joi'

     

    간단한 사용예시

    const express = require("express");
    const Joi = require("joi");
    
    const app = express();
    
    app.get("/api/user/:id", async (req, res) => {
        const { id } = req.params;
       
        // 규칙을 정해준다.
        const schema = Joi.number().min(100).require();
    
        try {
            // 검사시작
          	// validateAsync 는 비동기적인 체크가 가능하기 때문에 절차실행에 있어 좋다.
            await schema.validateAsync(id);   
        } catch (e) {
            // 유효성 검사 에러
            return res.status(400).json({ code: 400, message: e.message })
        }
    
        res.json({ code: 200 })
    })

     

    메세지를 사용하려면 이와같은 방식으로 사용해주어야한다 .

    joi.string().max(30).required().regex(emailRegExp).messages({
          "string.base": "Email은 문자열이어야 합니다.",
          "any.required": "Email을 입력해주세요.",
          "string.pattern.base": "Email이 형식에 맞지 않습니다.",
          //"string.min": "Email은 최소 5글자여야 합니다.",
          "string.max": "Email은 최대 30글자여야 합니다.",
        });

     

    또한 joi를 사용할때 많은 사용되는 메서드? 함수 ?

    string().max(30).required().regex(emailRegExp).messages
    
    stiring() : 문자열이 들어와야한다.
    
    Number() : 숫자열이 들어와야한다.
    
    requier() : 입력을 반드시 받아야한다.
    
    max() : 최대글자수 
    
    min() : 최소글자수
    
    regex() : 정규식표현

     

    그외의 사용방법들이 나열되어있다 .

    https://runebook.dev/ko/docs/joi/index

     

    Joi - function.class() [ko]

     

    runebook.dev

     

     

    코드적용

    import Joi from 'joi';
    
    const schema = Joi.object({
      restaurantName: Joi.string().required().messages({
        'any.required': '업장 이름을 입력해주세요.',
      }),
      restaurantAddress: Joi.string().required().messages({
        'any.required': '업장 주소를 입력해주세요.',
      }),
      restaurantType: Joi.string().required().messages({
        'any.required': '업장 종류를 입력해주세요.',
      }),
      restaurantPhoneNumber: Joi.string().required().messages({
        'any.required': '업장 전화번호를 입력해주세요.',
      }),
    });
    
    export const restaurantUpdateValidator = async (req, res, next) => {
      try {
        await schema.validateAsync(req.body);
        next();
      } catch (error) {
        next(error);
      }
    };

     

Designed by Tistory.