<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>正确的日期格式验证</h1>

<form action="">
<p>
出生日期:
<input type="text" name="birthday" id="birthday">
</p>
<p>
<input type="submit">
</p>
</form>
<script>

// 当表单提交时,验证
// 定义变量
let ele_form = document.querySelector("form")
let ele_ipt = document.querySelector("input#birthday")
console.log(ele_ipt)
// 事件绑定
ele_form.onsubmit = form_submit

// 事件详情
function form_submit() {
// 获得用户输入的内容
let value = ele_ipt.value
// xxxx-xx-xx
// 正则表达式验证,验证是否是日期
// xxxx-xx-xx
// xxxx-x-xx
// xxxx-x-x
// 验证1,内容格式是否合法
let re = /^\d{4}-\d{1,2}-\d{1,2}$/
let is_ok = re.test(value)
// 判断如果合法就提交,如果非法阻止提交
if (is_ok === false) {
return false
}

// 验证2,年月日是否合法
let [year, month, day] = value.split("-")

if (year < 1000 || year > 3000) {
alert("年份不合法")
return false
}
if (month < 1 || month > 12) {
alert("月份不合法")
return false
}
if (day < 1 || day > 31) {
alert("日期不合法")
return false
}

}

</script>
</body>
</html>