我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。


当前回答

 <input type="email" class="form-control" required="required" placeholder="Email Address" name="Email" id="Email" autocomplete="Email">
 <button class="btn-1 shadow-0 full-width" type="button" id="register">Register account</button>

 $("#register").click(function(){       
    var rea = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    var Email = $("#Email").val();
    var x = rea.test(Email);
    if (!x) {
        alert('Type Your valid Email');
        return false;
    }           
 </script>

其他回答

如果你想要一個人可以閱讀和維持的東西,我會推薦Masala Parser(我是它的創造者之一)。

import {C,Streams} from '@masala/parser'

const illegalCharset = ' @\u00A0\n\t';
const extendedIllegalCharset = illegalCharset + '.';


// Assume 'nicolas@internal.masala.co.uk'
export function simpleEmail() {

    return C.charNotIn(illegalCharset).rep() // 'nicolas'
        .then(C.char('@'))
        .then(subDns())  //'internal.masala.co.'
        .then(C.charNotIn(extendedIllegalCharset).rep()) //'uk'
        .eos(); // Must be end of the char stream
}

// x@internal.masala.co.uk => extract 'internal.masala.co.'
function  subDns() {
    return C.charNotIn(extendedIllegalCharset).rep().then(C.char('.')).rep()
}

function validateEmail(email:string) {
    console.log(email + ': ' + (simpleEmail().parse(Streams.ofString(email)).isAccepted()));
}


validateEmail('nicolas@internal.masala.co.uk'); // True
validateEmail('nz@co.'); // False, trailing "."

如果你想接受最终丑陋的电子邮件版本,你可以在第一部分添加引用:


function inQuote() {
    return C.char('"')
        .then(C.notChar('"').rep())
        .then(C.char('"'))
}

function allEmail() {

    return inQuote().or(C.charNotIn(illegalCharset))
        .rep() // repeat (inQuote or anyCharacter)
        .then(C.char('@'))
        .then(subDns())
        .then(C.charNotIn(extendedIllegalCharset).rep())
        .eos() // Must be end of the character stream
        // Create a structure
        .map(function (characters) { return ({ email: characters.join('') }); });
}

“Nicolas”“love-quotes”@masala.co.uk”是正式有效的,但应该在您的系统中吗?

至少与马萨拉,你给自己一个机会来理解它。

我更喜欢保持它简单,并让我的用户快乐,我也更喜欢易于理解的代码。

function isValidEmail(value) {
    const atLocation = value.lastIndexOf("@");
    const dotLocation = value.lastIndexOf("."); 
    return (
        atLocation > 0 &&
        dotLocation > atLocation + 1 &&
        dotLocation < value.length - 1
    );
};

确保“@”不是第一辆车(在前面有什么东西) 确保“”是“@”之后,并且他们之间至少有一辆车 确保“@”之后至少有一辆车。

这会允许无效的电子邮件地址通过吗?当然,但我不认为你需要更多的好用户体验,允许你启用/禁用一个按钮,显示错误消息等。

下面是MDN上推荐的Regex模式为HTML5:

支持电子邮件输入类型的浏览器自动提供验证,以确保仅符合互联网电子邮件地址标准格式的文本输入到输入框中。

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}
[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

https://developer.mozilla.org/en-US/docs/Web/HTML/元素/输入/电子邮件#验证

这个问题比一眼看起来更难回答。

世界各地有大量的人正在寻找“统治他们所有”,但事实是,有大量的电子邮件提供商。

为什么? 根据 RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification。

The local-part of the email address may use any of these ASCII characters:

- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6]
Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.

A__z/J0hn.sm{it!}h_comment@example.com.co

如果你尝试这个地址我赌它将失败在所有的或大部分的regex发布在整个网络上. 但记住这个地址遵循RFC规则,所以它是公平有效的。

想象一下我的失望,因为我无法在任何地方注册与这些 regex 检查!!!

如何处理,是的?

"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com

在这样做时,一个好做法是“重新输入您的电子邮件”输入,以避免用户输入错误,如果这对您来说不够,请添加一个提前提交的模型窗口,标题为“这是您的当前电子邮件吗?”然后用户输入的电子邮件在一个H2标签中,您知道,清楚地显示他们输入的电子邮件,然后一个“是的,提交”按钮。

有我的版本的电子邮件验证器. 这个代码是用对象导向的编程进行的,并作为一个类的静态方法实现。 你会发现两个版本的验证器:严格(EmailValidator.validate)和类型(EmailValidator.validateKind)。

第一個扔一個錯誤,如果一個電子郵件是無效的,並返回電子郵件不同. 第二個返回 Boolean 值,說一個電子郵件是有效的。

export class EmailValidator {
    /**
     * @param {string} email
     * @return {string}
     * @throws {Error}
     */
    static validate(email) {
        email = this.prepareEmail(email);

        const isValid = this.validateKind(email);

        if (isValid)
            return email;

        throw new Error(`Got invalid email: ${email}.`);
    }

    /**
     * @param {string} email
     * @return {boolean}
     */
    static validateKind(email) {
        email = this.prepareEmail(email);

        const regex = this.getRegex();

        return regex.test(email);
    }

    /**
     * @return {RegExp}
     * @private
     */
    static getRegex() {
        return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    }

    /**
     * @param {string} email
     * @return {string}
     * @private
     */
    static prepareEmail(email) {
        return String(email).toLowerCase();
    }
}

要验证电子邮件,您可以遵循以下方式:

// First way.

try {
    EmailValidator.validate('balovbohdan@gmail.com');
} catch (e) {
    console.error(e.message);
}
// Second way.

const email = 'balovbohdan@gmail.com';
const isValid = EmailValidator.validateKind(email);

if (isValid)
    console.log(`Email is valid: ${email}.`);
else
    console.log(`Email is invalid: ${email}.`);