<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../jquery-1.7.2/jquery.min.js"></script> <script> $(function(){ //onblur: 光標離開控件,會觸發onblur事件 $("#email").blur(function(){ var re = /^\w+@\w+(\.\w+){1,3}$/; if ( $(this).parent().find( "span" ).length > 0 ) { $(this).parent().find( "span" ).remove(); } if ( re.test( $(this).val() ) ) { $(this).after( "<span class='ok'>格式正確</span>" ); }else { $(this).after( "<span class='error'>格式錯誤</span>" ); } }); $("#pwd").blur(function(){ var re = /^\w{6,20}$/; if ( $(this).parent().find( "span" ).length > 0 ) { $(this).parent().find( "span" ).remove(); } if ( re.test( $(this).val() ) ) { $(this).after( "<span class='ok'>格式正確</span>" ); }else { $(this).after( "<span class='error'>格式錯誤</span>" ); } }); $("#reg :submit").click(function(){ $("#email").trigger("blur"); $("#pwd").trigger("blur"); if ( $("#reg").find(".error").length > 0 ) { return false; } }); }); </script> <style> .ok { color:green; } .error { color:red; } </style> </head> <body> <form action="http://www.baidu.com" method="get" id="reg"> <p class=emailParent> 郵箱: <input type="text" name="email" id="email"> </p> <p> 密碼: <input type="text" name="pwd" id="pwd"> </p> <p> <input type="submit" id="submit" value="注冊" > </p> </form> </body> </html>