轉載自《鋒利的Jquery》
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jq</title>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
</head>
<style type="text/css">
label{
width: 80px;
display: inline-block;
}
.high{
color: red;
display: none;
}
</style>
<body>
<form method="get">
<div class="int">
<label for='user'> 用戶名</label>
<input type="text" name="user" id="user" value="" class="required" autofocus="autofocus"/>
</div>
<div class="int">
<label for="email">郵 箱</label>
<input type="text" name="email" id="email" value="" class="required"/>
</div>
<div class="int">
<label for="personinfo">個人資料</label>
<input type="text" name="personinfo" id="personinfo" value="" class="required"/>
</div>
<div class="sub">
<input type="reset" name="reset" id="reset" value="重置" />
<input type="submit" value="登錄" id="submit"/>
</div>
</form>
</body>
<script type="text/javascript">
$(function(){
$('.required').each(function(){
$(this).parent().append("<strong class='high'>*</strong>");
})
});
//對需要填寫的選項進行驗證,驗證失敗時向div 中填入class爲onError的提示語句;
$("form .required").blur(function(){
$(this).parent().find(".formTips").remove();
$(this).parent().find(".high").css('display','none');
if($(this).is('#user')){
if(this.value=="" || this.value.length<=6){
$(this).parent().append('<span class="formTips onError">請輸入大於6位數的用戶名</span>');
$(this).next().css('display','inline');
}else{
$(this).parent().append('<span class="formTips">ok</span>');
}
}else if($(this).is("#email")){
var reg=/.+@.+\.[a-zA-Z]{2,4}$/;
if($(this).val()==''||!reg.test($(this).val())){
$(this).parent().append('<span class="formTips onError">請輸入正確的郵箱</span>');
$(this).next().css('display','inline');
}else{
$(this).parent().append('<span class="formTips">ok</span>');
}
}
})
//當點擊提示按鈕時,驗證表單中是否存在錯誤提示框;
$('#submit').click(function(){
$('form .required').trigger('blur'); //觸發blur 事件的jquery方法
var numError=$('form .onError').length;
if(numError){
//含錯誤提示框時,阻止表單提交
return false;
}
})
</script>
</html>