js 사용자 나이 제한

기여·2024년 6월 16일
0

소소한 개발팁

목록 보기
40/103

프론트엔 사용자가 입력할 내용에 대한 제약사항들은
다른 주요 기능 (crud) 테스트 다 마치고, 추가로 넣는 게 낫겠더라.

백엔드 위주로 공부 중이기도 하고,
테스트하면서 내가 정한 제한들 때문에 여러 차례로 킹받았으니 🤣

그 중의 하나는 연령이다.
그래도 관심 분야에 실제로 나이 제한이 있어서 기꺼이 진행~!

예제:

<script>
//나이 제한 scr
function validateAge() {
            const dobInput = document.getElementById('custDob').value;
            if (dobInput) {
                const dob = new Date(dobInput);
                const today = new Date();
                let age = today.getFullYear() - dob.getFullYear();
                const m = today.getMonth() - dob.getMonth();
                const d = today.getDate() - dob.getDate();

                // 만 나이 계산
                if (m < 0 || (m === 0 && d < 0)) {
                    age--;
                }

                if (age < 14) {
                    alert("신청일 기준 만 14세 이상만 신청 가능합니다.");
                    document.getElementById('custDob').value = ''; // 입력된 값 초기화
                    return false;
                }
            }
            return true;
        }

        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('custDob').addEventListener('change', validateAge);
        });
//나이 제한 scr 끝
</script>
			<th><p>생년월일:</p></th>
            <td><input class="input" type="date" name="custDob" id="custDob" required>
            <small>* 신청일 기준 만14세 이상만 신청 가능합니다.</small>
            </td>

결과:

profile
기기 좋아하는 여자

0개의 댓글