javascript正则表达式判断邮箱地址是否合法

设合法的邮箱地址格式为“字段1”@“字段2”.“字段3”
字段1为数字和任意字母的组合,中间可以有不连续出现的”.”,”-“,”_”出现
字段2只允许为字母和数字的组合
字段3只允许为字母

验证Email地址的正则表达式

'use strict';
var re = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
// 测试:
var
    i,
    success = true,
    should_pass = ['[email protected]', '[email protected]', '[email protected]', '[email protected]'],
    should_fail = ['test#gmail.com', 'bill@microsoft', 'bill%[email protected]', '@voyager.org'];
for (i = 0; i < should_pass.length; i++) {
    if (!re.test(should_pass[i])) {
        console.log('测试失败: ' + should_pass[i]);
        success = false;
        break;
    }
}
for (i = 0; i < should_fail.length; i++) {
    if (re.test(should_fail[i])) {
        console.log('测试失败: ' + should_fail[i]);
        success = false;
        break;
    }
}
if (success) {
    console.log('测试通过!');
}

可以验证并提取出带名字的Email地址:

var re = /^<([a-zA-Z]+\s+[a-zA-Z]+)>\s+([a-zA-Z0-9]+[-_\.]?@[a-zA-Z0-9]+\.[a-z]+)$/;

var r = re.exec(' [email protected]');
if (r === null || r.toString() !== [' [email protected]', 'Tom Paris', '[email protected]'].toString()) {
    console.log('测试失败!');
}
else {
    console.log('测试成功!');
}

参考文章:
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434499503920bb7b42ff6627420da2ceae4babf6c4f2000

你可能感兴趣的:(javascript)