2

I am currently working with AJAX/JS to have form without a button click or page refresh. The inquiry I have is in regards of email validation. Right now the PHP code checks if an email address is valid or not. I would like to only have it accept emails from a certain domain. How can I achieve through php to accept only email address from gmail? Example

PHP for validation of email:

if($_POST) {
    $email = $_POST['email'];
    if (preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email)) {
        echo ('<div id="email_input"><span id="resultval">'.$email.'</span></div>');
    }
    else {
        echo ('<div id="email_input"><span id="resultval">Include a valid email address.</span></div>');
    }
}
Nikola K.
  • 7,093
  • 13
  • 31
  • 39

3 Answers3

5

Php has an easy function to help you with checking if an email address is valid:

$isValid = filter_var($email, FILTER_VALIDATE_EMAIL);

To check if the email adress is a gmail address, the following would do the trick:

list ($user, $domain) = explode('@', $email);
$isGmail = ($domain == 'gmail.com');
Wouter
  • 833
  • 6
  • 13
4

Be careful with your regex, it won't validate all actual email addresses.

You have a built-in PHP function to check if an email is valid :

$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

If this returns true, then you just have to check if the string ends with @gmail.com. Note that there may be some strange issues with this function, because email validation standards can be surprising.

If you really want a regex which validates all email addresses, here it is :

(?:[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Community
  • 1
  • 1
Dalmas
  • 26,409
  • 9
  • 67
  • 80
2

You should change you're regular expression to this

'|^[A-Z0-9._%+-]+@gmail\.com$|i'
bkwint
  • 636
  • 4
  • 9