<!DOCTYPE HTML>
<html>
<head>
<title>javascript 나이 계산</title>
<style>
input {height:12px;}
p {display:inline;}
.nb {ime-mode: disabled;}
#y {width:30px;}
#m, #d {width:15px;}
#btn_age {height:20px;}
</style>
<script type="text/javascript">
// 숫자 확인
String.prototype.only_number = function(){
return this.replace(/[^0-9]/gi, '');
}
// 나이 계산
function fnAge()
{
var today = new Date();
var y = document.getElementById('y').value;
if(y == '' || y.length < 4)
{
alert('년도(예>1990)를 입력하세요.');
document.getElementById('age').innerText = '?';
document.getElementById('y').focus();
return false;
}
if(Number(y) < (today.getFullYear() - 150))
{
alert('나이가 너무 많습니다.');
document.getElementById('age').innerText = '?';
document.getElementById('y').focus();
return false;
}
if(Number(y) >= today.getFullYear())
{
alert('1살 이하입니다.');
document.getElementById('age').innerText = '?';
document.getElementById('y').focus();
return false;
}
var m = document.getElementById('m').value;
if(m == '' || m.length < 1 || (Number(m) < 1 || Number(m) > 12))
{
alert('월(예>1~12)을 입력하세요.');
document.getElementById('age').innerText = '?';
document.getElementById('m').focus();
return false;
}
var d = document.getElementById('d').value;
if(d == '' || d.length < 1 || (Number(d) < 1 || Number(d) > 31))
{
alert('일(예>1~31)을 입력하세요.');
document.getElementById('d').focus();
return false;
}
var birthday = new Date(m + '/' + d + '/' + y);
var years = today.getFullYear() - birthday.getFullYear();
// 현재 년도에서 생일을 재설정
birthday.setFullYear(today.getFullYear());
// 생일이 지났으면 -1
if(today < birthday)
{
years--;
}
document.getElementById('age').innerHTML = years;
}
</script>
</head>
<body>
<p>생년월일 : </p>
<input type="text" id="y" maxlength="4" class="nb" value="" onblur="this.value=this.value.only_number();" />년
<input type="text" id="m" maxlength="2" class="nb" value="" onblur="this.value=this.value.only_number();" />월
<input type="text" id="d" maxlength="2" class="nb" value="" onblur="this.value=this.value.only_number();" />일
/ 나이 : 만
<p id="age">?</p>살
<input type="button" id="btn_age" onclick="fnAge()" value="확인" />
</body>
</html>