본문 바로가기

Typescript

[Joi] 특정 필드 날짜보다 특정일을 초과하면 안되도록 설정하기

반응형

 

아래와 같이 startDate와 finishDate가 있다.

여기서 startDate와 finishDate가 최대 90일까지 가능하도록 (91일 부터는 설정이 되지 않도록) 만들기 

 

There are startDate, finishDate in the following box. I'd like to make the the max days between them 90 days. 

const validationSettings = {
  
  startDate: Joi.date()
    .required()
    .format('YYYY-MM-DD')
    .max(Joi.ref('finishDate'))
    .label('시작 날짜'),
  
  finishDate: Joi.date()
  	.required()
    .format('YYYY-MM-DD')
    .max('now')
    .label('종료 날짜'),
};

 

먼저 startDate에 Joi.ref('finishDate')가 이미 설정되어 있다. startDate의 최대값은 finishDate의 값이라는 것인데 이미 ref를 썼기 때문에 finishDate 에서 ----> startDate로 Joi.ref('startDate')이렇게 사용할 수가 없다. (순환금지) 

그래서 startDate에 adjust 함수를 사용해서 최대 90일까지 가능하도록 아래와 같이 설정할 수 있다. 

 

One important thing is that startDate already used "Joi.ref('finishDate')" so finishDate can not use "Joi.ref('startDate')" because two fields can not be in circulating functions.  Therefore we need to do something with startDate like below. 

 

const validationSettings = {

  startDate: Joi.date()
    .required()
    .format('YYYY-MM-DD')
    .max(Joi.ref('finishDate'))
    .min(
      Joi.ref('finishDate', {
        adjust: finishDate => new Date(finishDate.setDate(finishDate.getDate() - 89)),
      }),
    )
    .label('시작 날짜'),
    
  finishDate: Joi.date().required().format('YYYY-MM-DD').max('now').label('종료 날짜'),
};

 

90이 아닌 89인 이유는 직접 계산해보니 최대 일 수에 -1한 값이 딱 떨어졌다. finishDate의 날짜에 89일을 거꾸로 돌린 값을 startDate의 min 최소값으로 정한다. 

 

그럼 StartDate : 2022-04-01  / finishDate : 2022-06-30 (총 91일) => 에러남  ERROR

 StartDate : 2022-04-02  / finishDate : 2022-06-30 (총 90일) => 에러 안남  SUCCESS

 

최대 30일까지라고 하면 저기 89를 -> 29로 바꿔주면 된다. 

 

No matter how many days you want to make, just write the number -1 so that it can work like you intended. 

If the max is 90days => 89 

the max is 30 days => 29 

 

Please comment if you have a better way!

반응형