我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。
当前回答
如果您正在使用 Closure 您可以使用内置的 goog.format.Email 地址类型:
http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html
例如:
goog.format.EmailAddress.isValidAddrSpec("blah@blah.com")
请注意,通过阅读来源(上面的链接),您可以看到评论表示 IDN 不受支持,并且仅旨在覆盖大多数地址:
// This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name
其他回答
如果你正在使用NG模式和材料,这就是工作。
vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))';
使用常规表达式:
/^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/
例子:
function validateEmail(email) {
var re = /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/;
return re.test(email);
}
只允许 @,,
如果您正在使用 AngularJS,只需添加 type="email" 到输入元素:
https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
如果没有输入元素,可以动态创建:
var isEmail = $compile('<input ng-model="m" type="email">')($rootScope.$new()).
controller('ngModel').$validators["email"];
if (isEmail('email@gmail.com')) {
console.log('valid');
}
微软在 ASP.NET MVC 中提供的常规表达式是
/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/
我在这里写的,如果它是错误的 - 尽管它一直是完美的我的需求。
如何创建一个功能,将测试任何字符串对电子邮件的模式使用常规表达在JavaScript,因为我们知道电子邮件地址可以是相当不同的地区,如在英国和澳大利亚它通常以.co.uk 或.com.au 结束,所以我试图覆盖这些也,也检查字符串是否转移到功能,这样的东西:
var isEmail = function(str) {
return typeof str==='string' && /^[\w+\d+._]+\@[\w+\d+_+]+\.[\w+\d+._]{2,8}$/.test(str);
}
然后检查它是否像下面的电子邮件:
isEmail('alex@example.com'); //true
isEmail('alireza@test.co.uk'); //true
isEmail('peter.example@yahoo.com.au'); //true
isEmail('alex@example.com'); //true
isEmail('peter_123@news.com'); //true
isEmail('hello7___@ca.com.pt'); //true
isEmail('example@example.co'); //true
isEmail('hallo@example.coassjj#sswzazaaaa'); //false
isEmail('hallo2ww22@example....caaaao'); //false
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?