<!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|20)\d{2}\-((0?[1-9])|(1[0-2]))\-((0?[1-9])|([1-2]\d)|3[01])$/;
        if(pattern.test(val)) {
            var date = new Date(val);
            if(date < new Date("1919-12-31") || date > new Date()) {
                return false;
            }
            var month = val.substring(val.indexOf("-")+1,val.lastIndexOf("-"));
            return date && (date.getMonth()+1 == parseInt(month));
        }
        return false;
    }
    console.log(checkBirth("1919-3-18"));
    console.log(checkBirth("2019-3-18"));
    console.log(checkBirth("1923-4-31"));
    console.log(checkBirth("1923-2-29"));
    console.log(checkBirth("2016-2-29"));
</script>
</body>
</html>