<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>42度空间-从0到1分步实现一个出生日期校验的正则表达式-完整测试</title>
</head>
<body>
<div id="main"></div>
<script>
    console.log = function(val) {
        document.getElementById("main").innerHTML += val +"<br />";
    }
    var checkBirth = function (val) {
        var pattern = /^((?:19[2-9]\d{1})|(?:20(?:(?:0[0-9])|(?:1[0-8]))))\-((?:0?[1-9])|(?:1[0-2]))\-((?:0?[1-9])|(?:[1-2][0-9])|30|31)$/;
        var result = val.match(pattern);
        if(result != null) {
            var iYear = parseInt(result[1]);
            var month = result[2];
            var date = result[3];
            if(/^((0?[469])|11)$/.test(month) && date == '31') {
                return false;
            } else if(parseInt(month)  == 2){
                if((iYear % 4 ==0 && iYear % 100 != 0) || (iYear % 400 == 0)) {
                    if(date == '29') {
                        return true;
                    }
                }
                if(parseInt(date) > 28) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    console.log(checkBirth("2009-3-18"));
    console.log(checkBirth("1923-4-31"));
    console.log(checkBirth("1923-2-29"));
    console.log(checkBirth("2016-2-29"));
</script>
</body>
</html>