html表单验证

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单验证</title>
<style>
span{
color: #ccc;
display: none;
}
</style>
</head>
<body>
用户名:<input type="text" name="username" id="use"><span id="tit1">请输入6-18位的用户名</span> <br>
邮箱: <input type="text" name="email" id="Emal"><span id="tit2">请输入正确邮箱地址</span>

<script>
var E=document.getElementById('Emal');
var Sp=document.getElementById('tit2');
// 绑定事件 获取焦点事件 onfocus
E.onfocus=function(){
Sp.style.display='inline-block';
}
// 绑定失去焦点事件onblur
E.onblur=function(){
// console.log('失去了焦点');
// 获取用户输入的内容
var val=E.value;
// 写邮箱规则
var reg=/^[0-9a-zA-Z]+@[0-9a-zA-Z]+.(com|cn|org|net)$/;
// 接收匹配的返回值 成功返回true 如果格式不正确返回false
var T=reg.test(val);
console.log(T);
if(T==true){
Sp.innerHTML='邮箱格式正确';
Sp.style.color='green';

}else{
Sp.innerHTML='邮箱格式错误,请重新输入';
Sp.style.color='red';
}

}

</script>

</body>
</html>
原文地址:https://www.cnblogs.com/lyxdw/p/8877777.html