开发者

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

With Java开发者_如何学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

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).


You do not need to use regex for this.

You can see if a string contains another string using the indexOf method.

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:

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:

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

See the MDN docs for browser support.


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):

/^[^@\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


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.


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.


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>


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


For Yahoo domains (without username)

@(((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))


Domain name is mandatory like .com , .in , .uk It'll check update 2 letter after '.' 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.

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜