表单验证
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </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="personinfo">用户名:</label> <input type="text" id="personinfo"> </div> <div class="sub"> <input type="submit" value="提交" id="send"> <input type="reset" id="res"> </div> </form> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function(){ $("form :input.required").each(function(){ var $required=$("<strong class='high'>*</strong>"); $(this).parent().append($required); }); $('form :input').blur(function(){ var $parent=$(this).parent(); $parent.find(".formtips").remove(); //验证用户名 if($(this).is('#username')){ if(this.value==''||this.value.length<6){ var errormsg="请输入至少6位的用户名"; $parent.append('<span class="formtips onerror">'+errormsg+'</span>'); }else{ var okmsg='输入正确'; $parent.append('<span class="formtips onsuccess">'+okmsg+'</span>'); } } //验证邮箱 if($(this).is('#email')){ if(this.value==''||(this.value!=="" && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value))){ var errormsg="请输入正确的e-mail地址"; $parent.append('<span class="formtips onerror">'+errormsg+'</span>'); }else{ var okmsg='输入正确'; $parent.append('<span class="formtips onsuccess">'+okmsg+'</span>'); } } }).keyup(function(){ $(this).triggerHandler('blur'); }).focus(function){ $(this).triggerHandler('blur') }) $('#send').click(function(){ $("form .required:input").trigger("blur"); var numerror=$('form .onerror').length; if(numerror){ return false; } alert("注册成功,密码已发送到你的邮箱,请查收."); }) }) </script> </body> </html>