我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。
当前回答
Regex 确认电子邮件地址
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+
其他回答
我正在使用这个功能
/**
* @param {*} email
*/
export const validateEmail = email => {
return new RegExp(/[\w-]+@([\w-]+\.)+[\w-]+/gm).test(email);
};
如果你得到这个错误:使用常规表达式是安全敏感的。
这个解决方案是免费的“定期表达拒绝服务(ReDoS)”
Regex 可验证无电子邮件(ReDoS):
/^[a-z0-9](?!.*?[^\na-z0-9]{2})[^\s@]+@[^\s@]+\.[^\s@]+[a-z0-9]$/
请告诉我这个解决方案是否适合你,谢谢。
ES6 样品
const validateEmail=(email)=> /^(([^<>()\[\]\\.,;:\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,}))$/.test(email);
如果你想要一個人可以閱讀和維持的東西,我會推薦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”是正式有效的,但应该在您的系统中吗?
至少与马萨拉,你给自己一个机会来理解它。
我写了一个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);
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?