需求:前端先验证用户输入的数据格式是否正确
<style>
.test {
width: 300px;
height: 250px;
margin-left:100px;
border: 1px solid black;
}
p{
margin-left: 100px;
}
.name{
margin-top:30px;
margin-left: 20px;
}
.pwd{
margin-left: 20px;
}
#submit{
margin-left: 100px;
}
#home{
margin-left: 10px;
}
#pwd{
margin-left: 20px;
}
</style>
<body>
<div class="test">
<div class="name">
用户名:<input type="text" id="home"></div>
<p id="nametext"> </p>
<div class="pwd">
密码:<input type="password" id="pwd"></div>
<p id="pwdtext"> </p>
<input type="submit" value="登录" id="submit">
</div>
<script>
var btn=document.querySelector('#submit')
var p=document.getElementById("nametext")
console.log(p)
btn.onclick=function(){
var name=document.querySelector('#home')
var namevalue=name.value
var nametest=/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
if(nametest.test(namevalue)){
home.style.borderColor="green"
nametext.innerHTML="邮箱格式正确"
nametext.style.color="green"
}
else{
home.style.borderColor="red"
nametext.style.color="red"
nametext.innerHTML="邮箱格式错误"
}
}
</script>