验证电子邮件来自特定域/子域

时间:2014-01-27 08:16:19

标签: javascript html forms email

有人可以告诉我如何验证电子邮件地址来自某个域/子域,例如example.com或email.example.com。如果它不是来自任何这些域/子域,则无法提交表单。

这是我的表单html:

<form name="form" method="post" action="mail.php">
    <input name="email" type="email" id="email" placeholder="email@gmail.com" required>
    <input name="name" type="text" id="name" placeholder="name" required>
    <button type="submit" id="submit">Submit!</button>
</form>

请告诉我如何将其整合到上面的表格中

由于

这是我到目前为止所尝试的:

<form name="form" method="post" action="mail.php">
    <input name="email" type="email" id="email" placeholder="email@gmail.com" required>
    <input name="name" type="text" id="name" placeholder="name" required>
    <button type="submit" id="submit">Submit!</button>
</form>

 <script>
    function IsValidEmail(email)
    $(document).ready(function() {
        $("#form").submit(function() {
        var allowedDomains = [ 'x.com', 'y.com', 'z.com' ];
        if ($.inArray(str[0], allowedDomains) !== -1) {
             //acceptable
        }else{
             //not acceptable
        }
 </script>

mail.php文件

<?php
$to = $_POST["email"];
$name = $_POST["name"];
$subject = "Test mail";
$message = "Hello! This is a simple email message.\n
Name: $name\n
Email: $to\n
Sending IP: $_SERVER[REMOTE_ADDR]";
$from = "test@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

1 个答案:

答案 0 :(得分:0)

  

我在Allow only specific email address' domain to register through JQuery (preferably)

尝试了这个脚本

但是,您忘记了最相关的部分:在@符号之后获取该部分,并针对该数组测试 。您当前使用的str[0]仍未定义。

$("#form").submit(function() {
    var allowedDomains = [ 'x.com', 'y.com', 'z.com' ];
    var domain = $("#email").val().split("@")[1];
    if ($.inArray(domain, allowedDomains) !== -1) {
        //acceptable, do nothing
    } else{
        //not acceptable, prevent submit event
    }
});

还要注意你忘记了一些关闭的大括号......