<!DOCTYPE html> <html> <head> <title>表單驗證</title> <script src="../scripts/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ $("form :input.required").each(function(){ var $required = $("<strong class='high'>*</strong>"); $(this).parent().append($required); }); $("input").blur(function(){ var $parent = $(this).parent(); if($(this).is("#username")){ $parent.find(".formtips").remove(); if( this.value==""||this.value.length<6){ var errorMsg = "請輸入至少6位的用戶名."; $parent.append('<span class="formtips onError">'+errorMsg+'</span>');
//$(this).after(errorMsg); }else{ var okMsg = "輸入正確."; $parent.append('<span class="formtips onSuccess">'+okMsg+'</span>'); } } }); $("#send").click(function(){ $("form .required:input").trigger("blur"); var numError = $('form .onError').length; if(numError){ //任何非0的數像1 -1等都被認爲是真 return false; } alert(numError); }) }); </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="persioninfo">我的資料:</label> <input type="text" id="persioninfo" class="required" /> </div> <div class="sub"> <input type="submit" id="send" value="提交"/> <input type="reset" id="res"/> </div> </form> </body> </html>