Email Validation with JavaScript
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Validate email address in Javascript?
这是我的第一个帖子,我有一个小问题。我正试图验证表单上的电子邮件地址,但运气不好。我在网上找到了这个片段,但它似乎不起作用。我现在正在使用javascript来验证它。我通常不使用JS,所以需要帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <script type="text/javascript"> function ValidateEmail(inputText) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(inputText.value.match(mailformat)) { document.forms.emailform(); return true; } else { alert("You have entered an invalid email address!"); document.forms.emailform(); return false; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php $addemail .= ' <form method="post" action="cart2.php" name="emailform" onsubmit="return validateEmail"> '; $addemail .= ' E-mail Address: <input type="text" name="email" value="'.$row6['email'].'" size="19" /><input type="hidden" name="cartid" value="'.$cart.'" />'; if ( $emailerror != '' ) { $addemail .= '<img src="images/email_error.png" width="16" height="16" hspace="4" alt="E-mail Error" />'; } $addemail .= ' <input type="image" name="Add E-mail Address" alt="Add E-mail Address" src="images/addemail.gif" style="vertical-align:middle" /> </form> '; if ( $row6['email'] == '' ) { $emailpresent = 0; } else { $emailpresent = 1; } } $addemail .= ' </td> </tr> '; } ?> |
请看下面的示例,了解如何在JavaScript中完成此操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <html> <head> <script type="text/javascript"> <!-- function validateEmail() { var emailText = document.getElementById('email').value; var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/; if (pattern.test(emailText)) { return true; } else { alert('Bad email address: ' + emailText); return false; } } window.onload = function() { document.getElementById('email_form').onsubmit = validateEmail; } </head> <body> <form id="email_form"> <input type="text" id="email"> <input type="submit"> </form> </body> </html> |
编辑:
如果您确定您的网页用户使用的是与HTML5兼容的浏览器,则可以使用以下更整洁的示例来实现相同的目的:
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html> <body> <form> <input type="email" pattern="^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$"> <input type="submit"> </form> </body> </html> |
1 | onsubmit="return validateEmail()" |
您必须在validateemail之后添加括号才能调用它,否则它将假定您正在尝试返回一个方法。