效果图:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.msg-default{
background-color:#666;
color:#ffffff;
}
.msg-success{
background-color:#00ff00;
color:#ffffff;
}
.msg-error{
background-color:#ff0000;
color:#ffffff;
}
</style>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
function fun(node,style,msg){
$(node).next().removeClass().addClass(style);
$(node).next().text(msg);
}
//五个框获取焦点时的提示信息
$("#name").focus(function(){
fun(this,"msg-default","用户名长度在6到9位之间");
});
$("#pw").focus(function(){
fun(this,"msg-default","密码长度在6到12位之间");
});
$("#pwconfirm").focus(function(){
fun(this,"msg-default","密码长度在6到12位之间");
});
$("#email").focus(function(){
fun(this,"msg-default","请输入合法的邮箱地址");
});
$("#phone").focus(function(){
fun(this,"msg-default","请输入合法的手机号");
});
//五个框的格式验证
$("#name").blur(function(){
if($(this).val()==""){
fun(this,"msg-error","用户名不能为空");
}else if($(this).val().length<6){
fun(this,"msg-error","用户名不能少于6位");
}else{
fun(this,"msg-success","用户名格式正确");
}
});
$("#pw").blur(function(){
if($(this).val()==""){
fun(this,"msg-error","密码不能为空");
}else if($(this).val().length<6){
fun(this,"msg-error","密码不能少于6位");
}else{
fun(this,"msg-success","密码格式正确");
}
});
$("#pwconfirm").blur(function(){
var pw = $("#pw").val();
if($(this).val()!=pw){
fun(this,"msg-error","密码不一致");
}
else if($(this).val()==""){
fun(this,"msg-error","密码不能为空");
}
else if($(this).val().length<6){
fun(this,"msg-error","密码格式不正确");
}
else{
fun(this,"msg-success","密码正确");
}
});
$("#email").blur(function(){
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if($(this).val()==""){
fun(this,"msg-error","邮箱不能为空");
}else if(reg.test($(this).val())){
fun(this,"msg-success","邮箱格式正确");
}else{
fun(this,"msg-error","邮箱格式不正确");
}
});
$("#phone").blur(function(){
var regExp = /1[3|5|7][0-9]{9}/;
if($(this).val()==""){
fun(this,"msg-error","手机号不能为空");
}else if(!regExp.test($(this).val())){
fun(this,"msg-error","手机号格式不正确");
}else{
fun(this,"msg-success","手机号格式正确");
}
});
//按钮的提交点击事件
$("#btn").click(function(){
//获取span节点,判断节点上是否包含msg-success样式名称
var count = 0;
$("form>div").find("span").each(function(index,item){
if($(this).hasClass("msg-success")){
count++;
}
});
if(count==5){
//提交
}else{
//表单不提交
return false;
}
});
});
</script>
</head>
<body>
<form action="">
<div>
姓名: <input type="text" name="name" id="name" placeholder="请输入用户名">
<span></span>
</div>
<div>
密码: <input type="password" name="pw" id="pw" placeholder="请输入用户名">
<span></span>
</div>
<div>
确认密码: <input type="password" name="pwconfirm" id="pwconfirm" placeholder="请输入确认密码">
<span></span>
</div>
<div>
邮箱: <input type="text" id="email" name="email" placeholder="请输入邮箱">
<span></span>
</div>
<div>
电话: <input type="text" id="phone" name="phone" placeholder="请输入电话">
<span></span>
</div>
<input type="submit" value="提交" id="btn">
</form>
</body>
</html>