개요
HTML DOM의 input month required 속성은 폼(form)을 제출하기 전에 월(month) 입력 필드를 반드시 채워야 하는지 여부를 불러오거나 수정하는 기능을 합니다. 이 속성을 활용하면 사용자가 필수 정보를 입력하지 않은 채 폼을 제출하는 것을 막을 수 있어, 데이터 누락을 방지하고 폼 유효성 검사의 신뢰도를 높이는 데 매우 유용합니다.
문법(Syntax)
required 속성의 기본 문법은 다음과 같습니다.
1. required 값 반환하기
object.required
2. required 값 설정하기
object.required = true | false
값을 true로 설정하면 해당 월 입력 필드가 필수 항목이 되어 빈 값으로는 폼을 제출할 수 없고, false로 설정하면 선택 사항으로 변경됩니다.
예제(Example)
다음 예제를 통해 HTML DOM input month required 속성이 실제로 어떻게 동작하는지 확인해 보겠습니다.
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%)
center/cover no-repeat;
height:100%;
}
p{
font-weight:700;
font-size:1.1rem;
}
input{
display:block;
width:35%;
border:2px solid #fff;
background-color:transparent;
color:#fff;
font-weight:bold;
padding:8px;
margin:1rem auto;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:35%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.show{
font-size:1.5rem;
color:#db133a;
font-weight:bold;
}
</style>
</head>
<body>
<h1>DOM Input Month Required 속성 데모</h1>
<form action="">
<p>태어난 달을 선택해 주세요.</p>
<input type="month" class="monthInput" required>
<input type="submit" onclick="checkInput()">
</form>
<div class="show"></div>
<script>
function checkInput() {
var monthInput = document.querySelector(".monthInput");
if(monthInput.value === ''){
document.querySelector(".show").innerHTML="월을 선택해 주세요";
}
}
</script>
</body>
</html>
실행 결과(Output)
위 코드를 실행하면 아래와 같은 초기 화면이 출력됩니다.

이제 월을 선택하지 않은 상태에서 [제출(Submit)] 버튼을 클릭해 보세요. required 속성이 동작하여 빈 값으로는 폼이 제출되지 않고, 화면에 안내 메시지가 표시되는 것을 확인할 수 있습니다.

핵심 정리
- required 속성은 Boolean(true/false) 값을 반환하며, 필요에 따라 직접 설정할 수도 있습니다.
- true인 경우 월 입력 필드는 필수 항목이 되어 빈 값으로 폼 제출이 차단됩니다.
- JavaScript를 통해 동적으로 필수 여부를 제어할 수 있어, 상황에 따라 유연한 폼 유효성 검사를 구현할 수 있습니다.