views:

58

answers:

6

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

Anyone know of a Regex that will deliver the domain?

thxs

A: 

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>
Leniel Macaferi
+1  A: 

I don't think you need to use regex for this. You can use indexOf().

var s = emailAddress.indexOf("@yahoo.com");
if (s != -1) //this will be true if the address contains yahoo.com

To make sure you are searching the domain (in case someone's email is @[email protected]) you can split the address at the @ symbol and then again split the period. Then you can check if for 'yahoo' and 'com'.

styfle
Hmm. Are you sure that's valid JS? It's erroring
AnApprentice
@nobosh that's because there is no statement after the `if`. styfle has shown you how to test if yahoo.com is in the string - you supply what happens after that.
Alex JL
+1  A: 
/@yahoo.com\s*$/.test(mystring)

is true if the string ends in @yahoo.com (plus optional whitespace).

Tim Pietzcker
Thanks but Where does this go?
AnApprentice
A: 
var rx = /^([\w\.]+)@([\w\.]+)$/;
var match = rx.exec("[email protected]");
if(match[1] == "yahoo.com"){
 do something
}

second capturing group will contain the domain.

Markos
How does this work e2e?
AnApprentice
A: 

To check for a particular domain (yahoo.com):

/^[^@\s][email protected]$/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
casablanca
JS error on that, it says it's not a function
AnApprentice
Sorry, I mixed up the call to `match`. It's fixed now.
casablanca
A: 
>>> String(​'[email protected]').replace​​​​​​​​(/^[^@]*@/, '')
'yahoo.com'
Tobias Cohen