本段代碼舉了一個最簡單的表單驗證實例,就是判斷輸入框是否爲空而已,大家可以根據這個原理,加入正則表達式判斷,實現各種功能強大的表單驗證功能
<html>
<head>
<title>Validate empty fields</title>
<style type="text/css">
body{font-family:"Trebuchet MS",verdana;width:450px;}
.error{ color:red; }
#info{color:#008000;font-weight:bold; }
</style>
</head>
<body>
<form>
<fieldset>
<legend><strong>ersonal</strong></legend>
<table>
<tbody>
<tr>
<td>Name:* </td>
<td><input type="text" class="required" /></td>
</tr>
<tr>
<td>Address:* </td>
<td><input type="text" class="required"/></td>
</tr>
<tr>
<td>City: </td>
<td><input type="text"/></td>
</tr>
<tr>
<td>Country:* </td>
<td><input type="text" class="required"/></td>
</tr>
</tbody>
</table>
</fieldset>
<br/>
<span id="info"></span>
<br/>
<input type="button" value="Check" id="check" />
</form>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var dataValid=false;
$('#info').html('');//然後將結果提示也設置爲空;
$('.required').blur(function(){//對於required類的元素,如果失去焦點了,則....
var cur=$(this);//獲取當前元素
cur.next('span').remove();//然後將錯題提示的<span>給移走,不管他之前是什麼;
if($.trim(cur.val())=='')
{//判斷如果輸入爲空;
cur.after('<span class="error">Mandatory field!</span>');//則在輸入框後添加錯題提示信息;
dataValid=false;
}else{dataValid=true;}
});
$('#check').click(function(){//點擊了Check按鈕之後,執行....
if(dataValid)
{
$('#info').html('Validation OK');//提示通過驗證
}});
});
</script>
</body>
</html>
門戶網站源碼
該片段來自於http://www.huiyi8.com/webyuanma/menhu/
簡單的Jquery表單驗證
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.