验证告诉我所有的电子邮件地址都无效

时间:2014-01-17 18:00:01

标签: javascript regex

我不知道为什么它总是告诉我,即使它是正确的,也是一个无效的电子邮件地址。任何想法? Demo on JSfiddle

我的表格

  <form id="FormViewForm" method="post" action="/NewsletterMailer/subscribe/4" accept-charset="utf-8">
                <input type="hidden" name="_method" value="POST" />
                <input type="hidden" name="data[Form][id]" value="4" id="FormId" />
                <input type="hidden" name="data[Form][type]" value="1" id="FormType" />
                <input type="email" name="data[Form][e-mail]" value="" id="subscribe-email" placeholder="Enter your email..." required>
                    <input type="submit" value="+" class="large" id="subscribe-submit">
                        </form>

我的custom.js

$('#FormViewForm').submit(function() {
    validateEmail($('input').val());
    return false;
});

function validateEmail(email) {
    var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (re.test(email)) {
        if (email.indexOf('@c-e.com', email.length - '@c-e.com'.length) !== -1) {
            alert('Submission was successful.');
        } else {
            alert('Email must be a CE e-mail address (your.name@c-e.com).');
        }
    } else {
        alert('Not a valid e-mail address.');
    }
}

2 个答案:

答案 0 :(得分:4)

只是一个jQuery选择器问题,你错过了#

validateEmail($('#subscribe-email').val());

您的函数收到undefined作为电子邮件,正则表达式失败。

您也可以使用纯JavaScript。 (请注意,document.getElementById不需要#,这可能会造成混淆。)

validateEmail(document.getElementById('subscribe-email').value);

答案 1 :(得分:1)

请使用右侧选择器 如果您想将用户ID作为选择器

validateEmail($('#subscribe-email').val());

或者您也可以使用输入标签作为选择器

validateEmail($('input[type=email]').val());

id选择器对所有浏览器都很强大,也可以安全使用

请尝试此代码

$('#FormViewForm').submit(function() {
    validateEmail($('#subscribe-email').val());
    return false;
});

function validateEmail(email) {
    var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (re.test(email)) {
        if (email.indexOf('@c-e.com', email.length - '@c-e.com'.length) !== -1) {
            alert('Submission was successful.');
        } else {
            alert('Email must be a CE e-mail address (your.name@c-e.com).');
        }
    } else {
        alert('Not a valid e-mail address.');
    }
}