在将用户输入发送到服务器或尝试向其发送电子邮件之前,为了防止最基本的打字错误,我想在JavaScript中检查用户输入是否为电子邮件地址。 我该如何实现此目标?
在将用户输入发送到服务器或尝试向其发送电子邮件之前,为了防止最基本的打字错误,我想在JavaScript中检查用户输入是否为电子邮件地址。 我该如何实现此目标?
在我的情况下,我想避免使用~
和#
,这就是为什么我使用了另一种解决方案的原因:
function validEmail(email){
const regex = /^((?!\.)[\w\-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
return regex.test(email);
}
function validEmail(email){
const regex = /^((?!\.)[\w\-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
return regex.test(email);
}
const emails = [
'pio_pio@factory.com',
'~pio_pio@factory.com',
'pio_~pio@factory.com',
'pio_#pio@factory.com',
'pio_pio@#factory.com',
'pio_pio@factory.c#om',
'pio_pio@factory.c*om',
'pio^_pio@factory.com'
]
for(const email of emails){
document.write(email+' : '+validEmail(email)+'</br>');
}
\-
而不仅仅是-
来为您的浏览器端代码未来做好准备。 - DroidOS我正在寻找一个JS中的正则表达式,可以通过所有电子邮件地址测试用例:
email@example.com
有效的电子邮件
firstname.lastname@example.com
电子邮件地址字段中包含点号
email@subdomain.example.com
电子邮件中包含带有子域的点
firstname+lastname@example.com
加号被视为有效字符
email@192.0.2.123
域是有效的IP地址
email@[192.0.2.123]
方括号中的IP地址被视为有效
"email"@example.com
引号中的电子邮件被视为有效
1234567890@example.com
地址中的数字是有效的
email@domain-one.example
域名中的破折号是有效的
_______@example.com
地址字段中的下划线是有效的
email@example.name
.name
是有效的顶级域名
email@example.co.jp
顶级域名中的点也被视为有效(此处使用co.jp
作为示例)
firstname-lastname@example.com
地址字段中的破折号是有效的
这是正则表达式:
或者使用以下正则表达式:
Regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/
这里的大多数答案对于代码检查工具不友好,一团糟!其中一些也已经过时了!
花费了很多时间后,我决定使用名为email-validator
的外部库,在项目中轻松地通过npm安装并导入/引用它:
https://www.npmjs.com/package/email-validator
//NodeJs
const validator = require("email-validator");
validator.validate("test@email.com"); // true
//TypeScript/JavaScript
import * as EmailValidator from 'email-validator';
EmailValidator.validate("test@email.com"); // true
我更喜欢保持简洁并让我的用户感到满意。我还更喜欢易于理解的代码。而正则表达式则不是这样。
function isValidEmail(value) {
const atLocation = value.lastIndexOf("@");
const dotLocation = value.lastIndexOf(".");
return (
atLocation > 0 &&
dotLocation > atLocation + 1 &&
dotLocation < value.length - 1
);
};
这样是否会允许无效的电子邮件地址通过?当然会,但我认为为了良好的用户体验,你只需要用它来启用/禁用按钮、显示错误消息等。只有在尝试向该地址发送电子邮件时,才能确定电子邮件地址是否有效。
/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/
我在这里发布它,以防它有缺陷 - 尽管它一直完美地满足了我的需求。
/^([^@\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
function validateEmail(email){
var re = /^(([^<>()[]\\.,;:\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,}))$/;
return re.test(email);
}
<input type="email" name="email">
^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$
<!DOCTYPE html>
<html>
<head>
<title>Our Company</title>
<style>
.form-style {
color: #ccc;
}
</style>
</head>
<body>
<h1>Email Validation Form Example</h1>
<input type="text" name="email" id="emailInput" class="form-style">
<script>
function validateEmail(emailAddress) {
var regularExpression = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))){2,6}$/i;
return regularExpression.test(emailAddress);
}
function showEmailValidationState(event) {
if (validateEmail(event.target.value)) {
document.getElementById("emailInput").style.color = 'black';
}
}
document.getElementById("emailInput").addEventListener("keyup", showEmailValidationState);
</script>
</body>
</html>
// Very simple, non-library dependent client-side e-mail validator
var emailv = {
// Timeout handler for checkDelay()
to: null,
// The core function that takes a string and validates it
check : function(em){
// Check 1 - The split ensures there's only one @
var c1 = em.split('@').length == 2;
// Check 2 - Must be at least 1 dot too
var c2 = em.indexOf('.') > 0;
// Check 3 - ensures there's always something after a @ or dot
var c3 = !(em.slice(-1)=="@"||em.slice(-1)==".");
return (c1&&c2&&c3); // If all TRUE, great.
},
// Shortcut to quickly check any text input by dom id
checkById : function(inputId){
d = document.getElementById(inputId);
return d?emailv.check(d.value):false;
},
// Check delay for checking on real-time inputs
checkDelay: function(em){
clearTimeout(emailv.to);
emailv.to = setTimeout("emailv.checkDelayP2('"+em+"')",1000);
},
// Part two of Check delay
checkDelayP2: function(em){
if(emailv.check(em)){ // Javascript filter says it seems okay
// For sakes of this demo, pretend we are now making a background
// check to see if e-mail is taken. We tell the user to wait..
emailv.status("Wait..");
// Pretend the background check took 2 seconds
// and said e-mail was available
setTimeout("emailv.status('OK')",2000);
} else {
// Javascript say it's bad, mmmkay?
emailv.status("BAD E-mail");
}
},
status : function(s){
document.getElementById('emailstatus').innerHTML=s;
}
}
<h2>1 of 2 - Delayed check</h2>
<ul>
<li><strong>Waits until the user has stopped typing</strong></li>
<li>Useful for when you want to then send e-mail to background database to check if it exists.</li>
<li>Allows them 1 idle second before checking the e-mail address.</li>
</ul>
<input type="text" size="50" id="youremail" name="youremail" onkeyup="emailv.checkDelay(this.value)" onpaste="emailv.checkDelay(this.value)" />
<span id='emailstatus'></span>
<h2>2 of 2 - Instant Check</h2>
<input type="text" size="50" id="youremail2" name="youremail2" />
<a href="Javascript:void(0)" onclick="alert(emailv.checkById('youremail2')?'Seems okay to me':'This e-mail is dodgy')">Check e-mail</a>
避免限制过多变得复杂,不如避免让用户输入有效的电子邮件。
这只是我的观点!