我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。
当前回答
我的同事和我分享了这个雷格斯,我很喜欢它。
function isValidEmailAddress (email) {
var validEmail = false;
if (email) {
email = email.trim().toLowerCase();
var pattern = /^[\w-']+(\.[\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*?\.[a-zA-Z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/;
validEmail = pattern.exec(email);
}
return validEmail;
}
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
其他回答
如果您想要使用 JQuery 并想要具有现代化的方法,则使用 JQuery 输入面具与验证。
http://bseth99.github.io/项目/jquery-ui/5-jquery-masks.html
关于如何简单的jQuery输入面具的演示文稿在这里: http://codepen.io/anon/pen/gpRyBp
一个简单的输入面具的例子为日期 forexample 没有完整的验证
<input id="date" type="text" placeholder="YYYY-MM-DD"/>
还有剧本:
$("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD"});
这是由数千个网站使用的官方Rails指南提出的验证的JavaScript翻译:
/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
相对简单,但对大多数常见的错误进行测试。
测试了数千个电子邮件的数据集,并且有零的虚假负面 / 积极。
使用例子:
const emailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
emailRegex.test('email@example.com'); // true
// Multi-word domains
emailRegex.test('email@example.co.uk'); // true
emailRegex.test('email@mail.gmail.com'); // true
// Valid special characters
emailRegex.test('unusual+but+valid+email1900=/!#$%&\'*+-/=?^_`.{|}~@example.com') // true
// Trailing dots
emailRegex.test('email@example.co.uk.'); // false
// No domain
emailRegex.test('email@example'); // false
// Leading space
emailRegex.test(' email@example.com'); // false
// Trailing space
emailRegex.test('email@example.com '); // false
// Incorrect domains
emailRegex.test('email@example,com '); // false
// Other invalid emails
emailRegex.test('invalid.email.com') // false
emailRegex.test('invalid@email@domain.com') // false
emailRegex.test('email@example..com') // false
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])+
// Try this regular Expression by ES6 function
const emailValidate = (email) => {
const regexp= /^[\w.%+-]+@[\w.-]+\.[\w]{2,6}$/;
return regexp.test(email);
}
你不应该使用常规表达式来验证一个输入链来检查它是否是一个电子邮件. 它太复杂,不会覆盖所有案例。
现在,因为你只能覆盖90%的案例,写下这样的东西:
function isPossiblyValidEmail(txt) {
return txt.length > 5 && txt.indexOf('@')>0;
}
例如,‘aaa@’是有效的,但总体而言,你得到了胡萝卜,不要被带走......一个简单的90%的解决方案比一个不起作用的100%的解决方案更好。
世界需要更简单的代码。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?