Hello,

I have a login form and a user can register their email address. But I was wondering how do I only allow certain email domains able to register?

Like if I only want @gmail.com or @yahoo.com only


This is my code right now

/* Email error checking */
      $field = "email";  //Use field name for email
      if(!$subemail || strlen($subemail = trim($subemail)) == 0){
         $form->setError($field, "* Email not entered");
      }
      else{
         /* Check if valid email address */
         $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
                 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
                 ."\.([a-z]{2,}){1}$";
         if(!eregi($regex,$subemail)){
            $form->setError($field, "* Email invalid");
         }
         $subemail = stripslashes($subemail);
      }

Thank you

Here's a much better example. [SOURCE]

You can use another regular expression to decide whether to allow/deny the email address.

(\.([a-z]{3})$)

I'm no expert on these, but *I think* this will match ".com" at the end of the email address, so you'll need to work on how to match the sub-domains that you want to allow

**Edit=~ strpos() may do the job more easily. Look at this example from the php manual:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

And an even more useful example using strstr()

<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

Oh so I can use the second set of codes to work with whatever @domain.com I want the user to register in?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.