HTML源码:<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewpoint" content="width=device-width,initial-scale=1.0/>
<title>表单验证</title>
<script src="../jquery-3.3.1.js"></script>
<link rel="stylesheet" type="text/css" href="form.css"/>
<link rel="stylesheet" type="text/javascript" href="form.js"/>
</head>
<body>
<!--<div id="f1">-->
<form method="post" action="">
<div class="int">
<label for="username">用户名:</label>
<input type="text" id="username" class="required"/>
</div>
<div class="int">
<label for="email">邮箱:</label>
<input type="text" id="email" class="required"/>
</div>
<div class="int">
<label for="personinfo">个人资料:</label>
<input type="text" id="personinfo"/>
</div>
<div class="sub">
<input type="submit" value="提交" id="send"/><input type="submit" value="重置" id="res"/>
</div>
</form>
<!--</div>-->
</body>
</html>
jQ源码:<script type="text/javascript">
//必填星号提示
$("form:input.required").each(function(){
var $required=$("<strong class='high'>*</strong>");//创建元素
$(this).parent().append($required);//追加到文档中
});
$("form:input").blur(function(){//为表单元素添加失去焦点事件
var $parent=this.parent();
$parent.find(".formtips").remove();//删除以前的提醒元素
//验证用户名
if($(this).is("#username")){
if(this.value==""||this.value.length<6){
var errorMsg="请输入至少6位的用户名";
$parent.append("<span class='formtips onError'>"+errorMsg+"</span>");
}else{
var okMsg="输入正确";
$parent.append("<span class='formtips onSuccess'>"+okMsg+"</span>");
}
}
//验证邮箱
if($(this).is("#email")){
if(this.value==""||(this.value!=""&&!/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value))){
var errorMsg="请输入正确的邮箱地址";
$parent.append("<span class='formtips onError'>"+errorMsg+"</span>");
}else{
var okMsg="输入正确";
$parent.append("<span class='formtips onSuccess'>"+okMsg+"</span>");
}
}
}).keyup(function(){
$(this).triggerHandler("blur");
}).focus(function(){
$(this).triggerHandler("blur");
});
//判断是否可提交表单
$("#send").click(function(){
$("form.required:input").trigger("blur");
var numErr=$("form.onError").length;
if(numErr){
return false;
}
alert("注册成功");
});
</script>
css:.int{
background:;
border:none;
width:300px;
height:100px;
}
label{
cursor:pointer;
display:inline-block;
text-align:right;
float:left;
vertical-align:top;
width:10em;
margin-right:1em;
}
|