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


当前回答

如果你想要一個人可以閱讀和維持的東西,我會推薦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”是正式有效的,但应该在您的系统中吗?

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

其他回答

只是为了完整性,这里有另一个RFC 2822符合规则。

我的焦点

我写了一个JavaScript电子邮件验证器,完全兼容PHP的filter_var($值,FILTER_VALIDATE_EMAIL)实施。

https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js

import validateEmail from 'filter-validate-email'

const value = '...'
const result = validateEmail(value)

相当于:

<?php

$value = '...';
$result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);

這是從 http://codesnippets.joyent.com/posts/show/1917 偷走的

email = $('email');
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
  // Yay! valid
  return true;
}
else
  {return false;}

如果你正在使用NG模式和材料,这就是工作。

vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))';

Rnevius的(和同事)解决方案是辉煌的,但它允许添加Cyrillic,日本语,Emoticons和其他单码符号,一些服务器可能受到限制。

<unk> <unk> <unk> <unk> <unk> <unk> <unk> <unk>

<unk> <unk> <unk> <unk> <unk> <unk> <unk> <unk>