<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>www.escdns.com jquery教程之表单验证--胡振强</title>
<style type="text/css">
*{line-height:25px;font-size:14px;}
form{border:1px solid #CCC;background-color:#FFF;padding:5px;margin:0;width:800px;}
label{width:100px;text-align:right;}
.high{color:#FF0000;}
.error{color:#FF0000;background-color:#E8E8E8;border:1px solid #CCC;padding:3px 0;}
.ok{color:Green;}
</style>
<script type="text/javascript" src="jscript/jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function(){
var chemail=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
$("input.required").each(function(){
var $txt="<span class='high'>*</span>";
$(this).parent().append($txt);
})
$("form input.required").blur(function(){
var $parent=$(this).parent();
if($(this).is("#username"))
{
$(this).parent().find(".error").remove();
$(this).parent().find(".ok").remove();
if(this.value==""||this.value.length<6){
$parent.append("<span class='error'>用户名不合法,要求长度大于6</span>");
}
else
{
$parent.append("<span class='ok'>用户名输入正确!</span>");
}
}
if($(this).is("#email"))
{
$(this).parent().find(".error").remove();
$(this).parent().find(".ok").remove();
if(this.value==""||!chemail.test(this.value))
{
$parent.append("<span class='error'>邮箱地址不合法!</span>");
}
else
{
$parent.append("<span class='ok'>邮箱输入合法!</span>");
}
}
})
$("input.required").keyup(function(){
$(this).triggerHandler("blur");
}).focus(function(){
$(this).triggerHandler("blur");
})
$("#send").click(function(){
$("form input.required").trigger("blur");
var errNumber=$("form .error").length;
if(errNumber)
{
return false;
}
else
return true;
})
})
</script>
</head>
<body>
<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="reset" value="重置" id="res"/>
</div>
</form>
</body>
</html>
文章出处:http://www.escdns.com/Html/9960.html