我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。


当前回答

在您的验证函数中使用此代码:

var emailID = document.forms["formName"]["form element id"].value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
    alert("Please enter correct email ID")
    return false;
}

您可以使用 jQuery. 内部规则定义:

eMailId: {
    required: true,
    email: true
}

其他回答

<pre>
**The personal_info part contains the following ASCII characters.
1.Uppercase (A-Z) and lowercase (a-z) English letters.
2.Digits (0-9).
3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.**
</pre>
*Example of valid email id*
<pre>
yoursite@ourearth.com
my.ownsite@ourearth.org
mysite@you.me.net
xxxx@gmail.com
xxxxxx@yahoo.com
</pre>
<pre>
xxxx.ourearth.com [@ is not present] 
xxxx@.com.my [ tld (Top Level domain) can not start with dot "." ]
@you.me.net [ No character before @ ]
xxxx123@gmail.b [ ".b" is not a valid tld ]
xxxx@.org.org [ tld can not start with dot "." ]
.xxxx@mysite.org [ an email should not be start with "." ]
xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]
xxxx..1234@yahoo.com [double dots are not allowed
</pre>
**javascript mail code**

    function ValidateEmail(inputText)
    {
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(inputText.value.match(mailformat))
    {
    document.form1.text1.focus();
    return true;
    }
    else
    {
    alert("You have entered an invalid email address!");
    document.form1.text1.focus();
    return false;
    }
    }

只需检查输入的电子邮件地址是否有效,或者不使用 HTML。

<input type="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');
} 

Sectrean的解决方案工作得很好,但它失败了我的镜头,所以我添加了一些漏洞:

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); 
}

如果你只想做的是抓住最明显的合成错误,我会做这样的事情:

^\S+@\S+$

它通常捕获了用户所犯的最明显的错误,并确保表格主要是正确的,这就是JavaScript验证的所有内容。

EDIT:我们也可以在电子邮件中查看“。

/^\S+@\S+\.\S+$/