简体   繁体   English

用于确定电子邮件域的 JavaScript RegEx(例如 yahoo.com)

[英]JavaScript RegEx to determine the email's domain (yahoo.com for example)

With JavaScript I want to take a input 1st validate that the email is valid (I solved for this) 2nd, validate that the email address came from yahoo.com使用 JavaScript 我想输入第一个验证电子邮件是否有效(我解决了这个问题)第二个,验证电子邮件地址来自 yahoo.com

Anyone know of a Regex that will deliver the domain?任何人都知道将提供域的正则表达式?

thxs谢谢

var myemail = 'test@yahoo.com'

if (/@yahoo.com\s*$/.test(myemail)) {
   console.log("it ends in @yahoo");
} 

is true if the string ends in @yahoo.com (plus optional whitespace). 如果字符串以@yahoo.com结尾(加上可选的空格),则为true。

You do not need to use regex for this. 您不需要使用正则表达式。

You can see if a string contains another string using the indexOf method. 您可以使用indexOf方法查看字符串是否包含另一个字符串。

var idx = emailAddress.indexOf('@yahoo.com');
if (idx > -1) {
  // true if the address contains yahoo.com
}

We can take advantage of slice() to implement "ends with" like so: 我们可以利用slice()来实现“结束”,如下所示:

var idx = emailAddress.lastIndexOf('@');
if (idx > -1 && emailAddress.slice(idx + 1) === 'yahoo.com') {
  // true if the address ends with yahoo.com
}

In evergreen browsers, you can use the built in String.prototype.endsWith() like so: 在常绿浏览器中,您可以使用内置的String.prototype.endsWith(),如下所示:

if (emailAddress.endsWith('@yahoo.com')) {
    // true if the address ends with yahoo.com
}

See the MDN docs for browser support. 有关浏览器支持,请参阅MDN文档

function emailDomainCheck(email, domain)
{
    var parts = email.split('@');
    if (parts.length === 2) {
        if (parts[1] === domain) {
            return true;
        }
    }
    return false;
}

:) :)

To check for a particular domain (yahoo.com): 要检查特定域(yahoo.com):

/^[^@\s]+@yahoo.com$/i.test(email)
// returns true if it matches

To extract the domain part and check it later: 要提取域部分并在以后检查它:

x = email.match(/^[^@\s]+@([^@\s])+$/)
// x[0] contains the domain name

Try this: 尝试这个:

/^\w+([\.-]?\w+)*@\yahoo.com/.test("you@yahoo.com"); //Returns True
/^\w+([\.-]?\w+)*@\yahoo.com/.test("you@abc@yahoo.com"); //Returns false
/^\w+([\.-]?\w+)*@\yahoo.com/.test("you#abc@yahoo.com"); //Returns false
/^\w+([\.-]?\w+)*@\yahoo.com/.test("you/abc@yahoo.com"); //Returns false

Above are some test cases. 以上是一些测试用例。

对于Yahoo域名(无用户名)

@(((qc|ca)?\.yahoo\.com)|yahoo\.(com(\.(ar|au|br|co|hr|hk|my|mx|ph|sg|tw|tr|vn))?|ae|at|ch|es|fr|be|co\.(in|id|il|jp|nz|za|th|uk)|cz|dk|fi|de|gr|hu|in|ie|it|nl|no|pl|pt|ro|ru|se))

What about this? 那这个呢?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
  <head>

    <script type="text/javascript">

    var okd = ['yahoo.com'] // Valid domains...

    var emailRE = /^[a-zA-Z0-9._+-]+@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/

    function ckEmail(tst)
    {  
      var aLst = emailRE.exec(tst)
      if (!aLst) return 'A valid e-mail address is requred';
      var sLst = aLst[1].toLowerCase()
      for (var i = 0; i < okd.length; i++) {
          if (sLst == okd[i]) {
              return true
          }
      }

      return aLst[1];
    }

    var ckValid = ckEmail(prompt('Enter your email address:'))

    if (ckValid === true) {
        alert(ckValid)  // placeholder for process validated
    } else {
        alert(ckValid)  // placeholder for show error message
    }

    </script>
    <title></title>
  </head>
  <body>
  </body>
</html>
var rx = /^([\w\.]+)@([\w\.]+)$/;
var match = rx.exec("user@yahoo.com");
if(match[1] == "yahoo.com"){
 do something
}

second capturing group will contain the domain. 第二个捕获组将包含域。

>>> String(​'test@yahoo.com').replace​​​​​​​​(/^[^@]*@/, '')
'yahoo.com'

Domain name is mandatory like .com , .in , .uk It'll check update 2 letter after '.' 域名是强制性的,如.com,.in,.uk它会在'。'之后检查更新2个字母。 and '@' is also mandatory. '@'也是强制性的。

<!DOCTYPE html>
    <html>
    <body>
    <script>
    function validateEmail(email) {
        debugger;
        console.log(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 ture for .com , .in , .co  upto 2 letter after .
        console.log(re.test(String(email).toLowerCase()));
        return re.test(String(email).toLowerCase());
    }
    </script>

    <h2>Text field</h2>
    <p>The <strong>input type="text"</strong> defines a one-line text input field:</p>

    <form action="#" onSubmit="validateEmail(firstname.value)">
    First name:<br>
    <input type="email" name="firstname">
    <br>
    Last name:<br>
    <input type="text" name="lastname">
    <br><br>
    <input type="submit">
    </form>

    <p>Note that the form itself is not visible.</p>
    <p>Also note that the default width of a text field is 20 characters.</p>

    </body>
    </html>

After reading previous answers and checking https://caniuse.com/mdn-javascript_builtins_string_endswith , the simplest way to check domain of an email is String.prototype.endsWith() method.在阅读之前的答案并检查https://caniuse.com/mdn-javascript_builtins_string_endswith 后,检查电子邮件域的最简单方法是String.prototype.endsWith()方法。

A simple program to check different inputs can be like below:检查不同输入的简单程序如下所示:

function validateEmail(email: string): boolean {
    return email.endsWith("example.com");
}

const emailCheckResults = new Map<string, boolean>();

const emailsToCheck = ["test@example.com", "example.com@somethingelse.com", "attacker@somedomain.com"];
emailsToCheck.map((email) => {
    emailCheckResults.set(email, validateEmail(email));
});

Array.from(emailCheckResults.keys()).map((key) => {
    console.log(`Checked: ${key}, Result: ${emailCheckResults.get(key)}`);
});

This will result following:这将导致以下结果:

Checked: test@example.com, Result: true
Checked: example.com@somethingelse.com, Result: false
Checked: attacker@somedomain.com, Result: false

Approaches like using indexOf or split simply didn't seem to me clean.像使用indexOfsplit这样的方法在我看来并不干净。

I recommend using String.prototype.endsWith() method to avoid simple mistakes in regex, to improve readability and testability of the code, to reduce attack surface if this is used in an authentication system etc.我建议使用String.prototype.endsWith()方法来避免正则表达式中的简单错误,提高代码的可读性和可测试性,如果在身份验证系统中使用,则减少攻击面等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 删除电子邮件扩展名,但要保留“ @”,但忽略yahoo.com部分。 不打印出@符号 - Removing the email extension but want to keep the “@” but ignore the yahoo.com part. Not printing out the @ sign 电子邮件正则表达式验证JavaScript不应包含example.com - Email regex validation javascript should not contain example.com 如何从列表中删除@ yahoo.com并对其进行排序? - How do I remove the @yahoo.com from the list and sort it? 计算外部网页(例如msn.com,yahoo.com)上的HTML元素 - Counting HTML Elements on external webpages e.g. msn.com, yahoo.com nodejs-如果是yahoo.com,则request.get(url)返回二进制数据 - nodejs - request.get(url) returning binary data in case of yahoo.com 使用正则表达式使用JavaScript确定域 - Using a regex to determine domain using JavaScript Javascript:使用正则表达式将域与电子邮件地址进行比较 - Javascript: Using regex to compare a domain to the email address JavaScript:如何在同一域中从“example.com/page1”重定向到“example.com/page2”? - JavaScript: how to redirect from “example.com/page1” to “example.com/page2” in same domain? 正则表达式 (Javascript) 用于解析带有 firstname.lastname.randomnumber@email.com 的电子邮件 - Regex (Javascript) for parsing email with firstname.lastname.randomnumber@email.com 使用JavaScript Regex将“ First.Last@example.com”转换为“ flast” - Make 'First.Last@example.com' into 'flast' with JavaScript Regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM