Home
All Posts
👹

[캘린더 라이브러리] 사용자가 2024/n/n 라고 입력해도 2024/0n/0n 로 찍히게 하기

Created
2024/03/14
Category
Troubleshoot
3 more properties

기존 코드

각 년, 월, 일의 문자열을 숫자로 변환한 뒤, 숫자를 두 자리 문자열로 변환하는 시도를 했다.
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { const dateRegex = /^\d{4}\/\d{1,2}\/\d{1,2}$/; const isValidFormat = dateRegex.test(dateInput); if (isValidFormat) { const parts = dateInput.split('/'); const year = parseInt(parts[0], 10); // 년 문자열을 숫자로 변환 const month = parseInt(parts[1], 10); // 월 문자열을 숫자로 변환 const day = parseInt(parts[2], 10); // 일 문자열을 숫자로 변환 // 숫자를 두 자리 문자열로 변환 const monthStr = month < 10 ? `0${month}` : `${month}`; const dayStr = day < 10 ? `0${day}` : `${day}`; // dateObj라는 날짜 객체를 생성하여 유효한 날짜인지 검사 const dateObj = new Date(year, month - 1, day); const isValidDate = dateObj.getFullYear() === year && dateObj.getMonth() === month - 1 && dateObj.getDate() === day; if (isValidDate) { // 날짜가 유효하면 변환된 형식으로 상태 업데이트 const formattedDate = `${parts[0]}/${monthStr}/${dayStr}`; setDisplayDate(formattedDate); setIsInputValid(true); } // ...
TypeScript
복사

기존 코드의 문제

하지만 모든 월과 일이 두 자리 혹은 한 자리가 아니니, 이를 특정 형식으로 포맷팅 후, 유효성 검사를 통해 업데이트를 해주어야겠다는 생각이 들었다.

수정한 코드

사용자가 입력한 날짜에서 년, 월, 일을 추출한 후, 숫자로 변환하고, 날짜 객체를 생성해 유효성 검사 후 포맷팅된 상태로 업데이트 했다. 이때 padStart() 라는 메서드를 사용해 각 년은 4자리, 월은 2자리, 일은 2자리로 맞추었다.
참고로 padStart() 는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환하는 메서드다.
const handleKeyDown= (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { const dateRegex = /^\d{4}\/\d{1,2}\/\d{1,2}$/; const isValidFormat = dateRegex.test(dateInput) if (isValidFormat) { // 입력된 날짜에서 년, 월, 일을 추출 const [yearStr, monthStr, dayStr] = dateInput.split('/'); // 년, 월, 일을 숫자로 변환 const year = parseInt(yearStr, 10); const month = parseInt(monthStr, 10); const day = parseInt(dayStr, 10); // 날짜 객체를 생성하여 유효성 검사 const dateObj = new Date(year, month - 1, day); const isValidDate = dateObj.getFullYear() === year && dateObj.getMonth() === month - 1 && dateObj.getDate() === day; if (isValidDate) { // 포맷팅된 날짜로 상태 업데이트 ✅ padStart() 사용 const formattedDate = `${yearStr.padStart(4, '0')}/${monthStr.padStart(2, '0')}/${dayStr.padStart(2, '0')}`; setDisplayDate(formattedDate); // DateInputContainer에 표시될 날짜를 업데이트 setDateInput(formattedDate); setIsInputValid(true); } // ...
TypeScript
복사

참고 자료