<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>前端校验:用户注册</title>
<style>
input:invalid {
background-color:red;
}
input:focus:invalid{
background-color:white;
}
</style>
</head>
<body>
<form id="registerForm">
<table>
<tr>
<td><label for="username">请设置用户名</label></td>
<td><input type="text" id="username" name="username" required pattern="^[^\s'"]{1,20}$"></td>
<td>1-20个字符,不可以包含空格、引号</td>
</tr>
<tr>
<td><label for="password">请设置密码</label></td>
<td><input type="password" id="password" name="password" required pattern="^[0-9a-zA-Z]{6,12}$"></td>
<td>6-12个数字、大小写字母的组合</td>
</tr>
<tr>
<td><label for="birthday">出生日期</label></td>
<td><input type="date" id="birthday" name="birthday" min="1900-01-01" required></td>
<td></td>
</tr>
</table>
<input type="submit" value="提交">
</form>
</body>
<script>
var password=document.getElementById("password");
var birthday=document.getElementById("birthday");
var form=document.getElementById("registerForm");
//1、用ajax做用户名校验(略)
//2、自定义密码校验的提示信息(前端校验方法一)
password.addEventListener("input",checkPassword);
password.addEventListener("invalid",customMessage);
function checkPassword(){
password.setCustomValidity("");
password.checkValidity();
}
function customMessage(){
if(password.validity.valueMissing){
password.setCustomValidity("您必须设置一个密码");
}
else if(password.validity.patternMismatch){
password.setCustomValidity("请设置正确的密码格式:6-12个数字、大小写字母的组合");
}else{
password.setCustomValidity("");
}
}
//3、自定义出生日期的提示信息(前端校验方法二)
form.addEventListener("submit",checkBirthday1);
birthday.addEventListener("change",checkBirthday2);
function checkBirthday1(event){
if(birthday.checkValidity()){
birthday.setCustomValidity("");
}else{
showErro();
event.preventDefault();
}
}
function checkBirthday2(){
if(birthday.checkValidity()){
birthday.setCustomValidity("");
}else{
showErro();
}
}
function showErro(){
if(birthday.validity.valueMissing){
birthday.setCustomValidity("请输入您的生日");
}else if(birthday.validity.rangeOverflow){
birthday.setCustomValidity("您必须年满18周岁才能注册");
}else if(birthday.validity.rangeUnderflow){
birthday.setCustomValidity("日期非法");
}else{
birthday.setCustomValidity("请输入一个有效值");
}
birthday.reportValidity();
}
window.onload=function(){
setMaxBirthday();
}
function setMaxBirthday(){
var nowDate=new Date();
var year=nowDate.getFullYear()-18;
var month=nowDate.getMonth()+1;
var date=nowDate.getDate();
birthday.max=year+"-"+"0"+month+"-"+date;
}
</script>
</html>
我预期的效果:如果没有输入生日,前端校验报错“请输入您的生日”
实际表现的效果:如果没有输入生日,前端校验报错“请填写此字段”
为何setCustomValidity()的效果没有实现?