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


当前回答

我正在使用 match() 来检查标准电子邮件模式,并在输入文本中添加一个类,以通知用户。

$(document).ready(函数(){ $('#submit').on('click',函数(){ var email = $('#email').val(); var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (email.match(pat)){ $('#email').addClass('input-valid'); return false; } else { $('#email').addClass('input-error').val(''); return false

其他回答

有一些复杂的RegEx写在这里,这也工作。

我试过这个,它也工作了:

[a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6}

请点击此处: http://www.regextester.com/?fam=97334

希望这能帮助。

\b[a-z][\w\d_\.]+@\w+\.[a-z]{2}[a-z]?\.?[a-z]{,2}\s

它允许:

abcxyz123@qwert.com    
abc123xyz@asdf.co.in   
abc1_xyz1@gmail1.com   
abc.xyz@gmail.com.in
     // Html form call function name at submit button

    <form name="form1" action="#"> 
    <input type='text' name='text1'/>
    <input type="submit" name="submit" value="Submit" 
    onclick="ValidateEmail(document.form1.text1)"/>
   </from>

    // Write the function name ValidateEmail below

    <script>
     function ValidateEmail(inputText)
    {
  var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
    if(inputText.value.match(mailformat))
    {
    alert("Valid email address!");
    document.form1.text1.focus();
    return true;
    }
    else
   {
    alert("You have entered an invalid email address!");
    document.form1.text1.focus();
    return false;
    }
    }
   </script>

这里的大多数答案不友好,这是一个混乱! 其中一些也过时了! 花了很多时间后,我决定使用一个名为电子邮件验证器的外部图书馆,通过 npm 轻松安装,例如,并在自己的项目中进口/要求:

https://www.npmjs.com/包装/电子邮件验证器

//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

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

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
}