1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> 3 4 <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <title>表单校验</title> 8 <meta name="author" content="Administrator" /> 9 <script type="text/javascript" src="script/jquery-1.12.2.js"></script> 10 <style type="text/css"> 11 .int { 12 margin-bottom: 5px; 13 } 14 .sub { 15 padding-left: 7%; 16 } 17 </style> 18 <!-- Date: 2016-04-03 --> 19 </head> 20 <body> 21 <form action="" method="post"> 22 <div class="int"> 23 <label for="username">用户名:</label> 24 <input type="text" id="username" class="required" /> 25 </div> 26 27 <div class="int"> 28 <label for="email"> 邮箱:</label> 29 <input type="text" id="email" class="required" /> 30 </div> 31 32 <div class="int"> 33 <label for="personinfo">个人资料</label> 34 <input type="text" id="personinfo" /> 35 </div> 36 37 <div class="sub"> 38 <input type="submit" value="提交" id="send" /> 39 <input type="reset" id="res" /> 40 </div> 41 </form> 42 <script type="text/javascript"> 43 $(function() { 44 //为必填的内容加*。 45 $("form :input.required").each(function() { 46 var $required = $("<strong class='high'>*</strong>"); 47 $(this).parent().append($required); 48 }); 49 //为每个文本框失去焦点时做校验。 50 $("form :input").blur(function() { 51 var $parent = $(this).parent(); 52 $parent.find(".formtips").remove(); 53 //验证用户名 54 if($(this).is("#username")){ 55 if(this.value==""||this.value.length<6){ 56 var errorMsg = "请输入至少6位的用户名。"; 57 $parent.append("<span class='formtips onError'>"+ errorMsg+"</span>"); 58 }else{ 59 var okMsg = "输入正确"; 60 $parent.append("<span class='formtips onSuccess'>"+okMsg+"</span>"); 61 } 62 } 63 //验证邮箱 64 if($(this).is("#email")){ 65 if(this.value==""||(this.value!=""&& !/.+@.+\.[a-zA-Z] {2,4}$/.test(this.value))){ 66 var errorMsg = "请输入正确的邮箱地址。"; 67 $parent.append("<span class='formtips onError'>"+ errorMsg+"</span>"); 68 }else{ 69 var okMsg = "请输入正确的邮箱地址。"; 70 $parent.append("<span class='formtips onSuccess'>"+okMsg+"</span>"); 71 } 72 } 73 }); 74 }); 75 </script> 76 </body> 77 </html>