廖雪峰JavaScript練習題3
阿新 • • 發佈:2018-11-27
請嘗試寫一個驗證Email地址的正則表示式。版本一應該可以驗證出類似的Email:
正則表示式:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> var re = /^[a-z]{1,8}\.?[0-9]{0,5}[a-z]{0,6}\@[a-z]{0,10}[0-9]{0,4}\.[a-z]{3}/ var i,success = true,should_pass = ['[email protected]', '[email protected]', '[email protected]', '[email protected]'],should_fail = ['test#gmail.com', '[email protected]', 'bill%[email protected]', '@voyager.org']; for (i = 0; i < should_pass.length; i++) { if (!re.test(should_pass[i])) { console.log('測試失敗: ' + should_pass[i]); success = false; break; } } for (i = 0; i < should_fail.length; i++) { if (re.test(should_fail[i])) { console.log('測試失敗: ' + should_fail[i]); success = false; break; } } if (success) { console.log('測試通過!'); } </script> </body> </html>