<!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>