使用 JavaScript 理解电子邮件验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15017052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
understanding email validation using JavaScript
提问by AlwaysALearner
I am new to JavaScript and found this JavaScript code in the internet that validates the given email (no issue with the code) -
我是 JavaScript 的新手,在互联网上发现了这段 JavaScript 代码来验证给定的电子邮件(代码没有问题)-
<html>
<h2>Email Validation</h2>
<script language = "Javascript">
function checkEmail(emailId) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailId)){
document.write("You have entered valid email.");
return true;
}
return false;
}
function ValidateEmail(){
var emailID=document.form.email;
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (checkEmail(emailID.value)==false){
emailID.value=""
alert("Invalid Email Adderess");
emailID.focus()
return false
}
alert('valid');
return true
}
</script>
<form name="form" method="post" onSubmit="return ValidateEmail()">
Enter an Email Address : <input type="text" name="email" size="30"><br>
<input type="submit" name="Submit" value="Submit">
</form>
</html>
I have no issues with the code, but I somehow failed to understand what the regular expression /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
means. I don't understand what each and every part of regular expression means. Please enlighten me.
我对代码没有问题,但不知何故我无法理解正则表达式的/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
含义。我不明白正则表达式的每一部分是什么意思。请赐教。
回答by Siddiqui
The two forward-slashes /.../ contains a regexe.
The leading ^ and trailing $ match the beginning and the ending of the input string, respectively. That is, the entire input string shall match with this regexe, instead of a part of the input string.
\w+ matches 1 or more word characters (a-z, A-Z, 0-9 and underscore).
[.-] matches character . or -. We need to use . to represent . as . has special meaning in regexe. The \ is known as the escape code, which restore the original literal meaning of the following character.
[.-]? matches 0 or 1 occurrence of [.-].
Again, \w+ matches 1 or more word characters.
([.-]?\w+)* matches 0 or more occurrences of [.-]?\w+.
The sub-expression \w+([.-]?\w+)* is used to match the username in the email, before the @ sign. It begins with at least one word character (a-z, A-Z, 0-9 and underscore), followed by more word characters or . or -. However, a . or - must follow by a word character (a-z, A-Z, 0-9 and underscore). That is, the string cannot contain "..", "--", ".-" or "-.". Example of valid string are "a.1-2-3".
The @ matches itself.
Again, the sub-expression \w+([.-]?\w+)* is used to match the email domain name, with the same pattern as the username described above.
The sub-expression .\w{2,3} matches a . followed by two or three word characters, e.g., ".com", ".edu", ".us", ".uk", ".co".
(.\w{2,3})+ specifies that the above sub-expression shall occur one or more times, e.g., ".com", ".co.uk", ".edu.sg" etc.
两个正斜杠 /.../ 包含一个正则表达式。
开头的 ^ 和结尾的 $ 分别匹配输入字符串的开头和结尾。也就是说,整个输入字符串应与此正则表达式匹配,而不是输入字符串的一部分。
\w+ 匹配 1 个或多个单词字符(az、AZ、0-9 和下划线)。
[.-] 匹配字符 . 或者 -。我们需要使用 . 来代表。作为 。在正则表达式中具有特殊意义。\ 被称为转义码,它恢复了后面字符的原始字面意思。
[.-]?匹配 0 或 1 次出现的 [.-]。
同样,\w+ 匹配 1 个或多个单词字符。
([.-]?\w+)* 匹配 0 次或多次出现的 [.-]?\w+。
子表达式 \w+([.-]?\w+)* 用于匹配电子邮件中 @ 符号之前的用户名。它以至少一个单词字符(az、AZ、0-9 和下划线)开头,然后是更多的单词字符 或 。或者 -。然而,一个 . 或 - 后面必须跟一个单词字符(az、AZ、0-9 和下划线)。也就是说,字符串不能包含“..”、“--”、“.-”或“-.”。有效字符串的示例是“a.1-2-3”。
@ 匹配自身。
同样,子表达式 \w+([.-]?\w+)* 用于匹配电子邮件域名,其模式与上述用户名相同。
子表达式 .\w{2,3} 匹配一个 . 后跟两个或三个单词字符,例如“.com”、“.edu”、“.us”、“.uk”、“.co”。
(.\w{2,3})+ 指定上述子表达式应出现一次或多次,例如“.com”、“.co.uk”、“.edu.sg”等。
回答by Steven Schobert
Here's a break down of the regular expression piece-by-piece:
以下是对正则表达式的逐个分解:
/^
=> beginning of a line
/^
=> 行首
\w+
=> any word (letters, numbers, and underscores) repeated 1 or more times
\w+
=> 重复 1 次或多次的任何单词(字母、数字和下划线)
([\.-]?\w+)*
=> a groupof [an optional period (.) or dash (-) followed by any word repeated one or more times]that can be repeated 0 or more times
([\.-]?\w+)*
=>一组的[任选的周期或短划线(。)( - ),然后通过任何字重复一次或更多次]可以重复0次或多次
@\w+
=> an at symbol (@) follow by any word repeated one or more times
@\w+
=> at 符号 (@) 后跟重复一次或多次的任何单词
([\.-]?\w+)*
=> a groupof [an optional period or dash followed any word repeated 1 or more times]that can be repeated 0 or more times
([\.-]?\w+)*
=> 一组可以重复 0次或多次的[一个可选句点或破折号后跟任何重复 1 次或多次的任何单词]
(\.\w{2,3})+
=> a groupof [a period followed by any word that can be repeated 2-3times]that can be repeated 1 or more times
(\.\w{2,3})+
=>一组可以重复1次或多次的[一个句号后跟任何可以重复2-3次的词]
$/
=> the end of a line
$/
=> 一行的结尾
By the way, here is a reallygood Introduction to Regular Expressionsavailable on Codular.
回答by aizaz
Try this
试试这个
E-mail: <input type="email" name="usremail">
E-mail: <input type="email" name="usremail">
It worked for me
它对我有用
回答by Roger Dannenberg
This validation code is WRONG for email addresses. In particular is does not allow addresses of the form [email protected]. This is widespread error found on many commercial websites (but not stackoverflow -- congratulations!).
此验证码对于电子邮件地址是错误的。特别是不允许格式为 [email protected] 的地址。这是在许多商业网站上发现的普遍错误(但不是 stackoverflow——恭喜!)。
回答by Ravi Gadag
here you go. a visualizer for regex
干得好。正则表达式的可视化工具
Regex Visualizerand A JS Fiddle
Regex Explained
正则表达式可视化工具和正则JS Fiddle
表达式解释
回答by user2217814
/^(\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+[,;]?[ ]?)+$/
this little beauty will allow you to enter one or more email addresses in a string, ending with a comma or semicolon, followed by an optional space. :)
这个小功能将允许您在一个字符串中输入一个或多个电子邮件地址,以逗号或分号结尾,后跟一个可选的空格。:)
回答by Miqayel
function validchat(){
$('#btn-input-email').blur(function() {
if($(this).val() != '') {
var pattern = /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i;
if(pattern.test($(this).val())){
$(this).css({'border' : '1px solid #569b44'});
$('#valid').text('');
} else {
$(this).css({'border' : '1px solid #ff0000'});
$('#valid').text('Не верно');
}
} else {
$(this).css({'border' : '1px solid #ff0000'});
$('#valid').text('Поле email не должно быть пустым');
}
});
$("#btn-input-text").blur(function() {
var textlength = $(this).val().trim().length;
if( textlength < 2 ){
$(this).css({'border' : '1px solid #ff0000'});
$('#validtext').text('Минимум 2 символ');
}else{
$(this).css({'border' : '1px solid #569b44'});
$('#validtext').text('');
}
});
var valid = $('#valid').text();
var validtext = $('#validtext').text();
if((!valid || valid == '') && (!validtext || validtext == '')){
return true;
}
}
validchat();
function AjaxChat () {
$('#btn-input-email , #btn-input-text').blur();
var valid = validchat();
if(valid){
var email = $('#btn-input-email').val();
var text = $('#btn-input-text').val();
var data = {
email:email,
text:text
}
$.ajax({
url: location.origin+"/chat_block.php",
//dataType: "json", ////Тип данных
type: "POST",
async: false,
data: data,
success: function(html) {
if(!html || html == 'null') AjaxChat ();
if (jQuery.html != "") {
var b_chat = $('.chat-customer').html();
var chat = 'Вы: ';
var obj = $.parseJSON(html);
chat += '<span>';
chat += obj['text'];
chat += '</span>';
chat += '<br /><br />';
$('.chat-customer').html(b_chat + chat);
$('#btn-input-text , #btn-input-email').val("");
}
},
error: function() {
//cosole.log('No result');
}
});
$('#btn-input-email').remove();
}
}