zbludd
zbludd

Reputation: 37

How do I validate an e-mail address so that it must have a .edu ending domain name only?

I am looking to validate e-mail addresses, only allowing e-mails ending with with an @ucla.edu

This is my current function.

Code:

function validate_email($email)
{
if (strlen($email) < 4  ||  strlen($email) > 64)
return 1;
elseif (!preg_match("/^([a-z0-9_\-]+)(\.[a-z0-9_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i",
$email))
        return 2;
    else
        return 0;
}
// End function

Upvotes: 0

Views: 268

Answers (4)

sujai
sujai

Reputation: 13

You can use substring in your case. Use the below code to validate email based on @ulca.edu:

function validate_email($email)
{  
    $pattern = "@ulca.edu";
    $validate = substr($email, -9);
    if($pattern == $validate )
    {
       //your code to allow email
    } 
    else
    {
     //dont allow 
    }
}

Upvotes: 0

Steve B
Steve B

Reputation: 644

One option if you are going to end up writing a lot of validation is to use an existing library to handle the bulk of the work for you. A good one to use is:

https://github.com/Respect/Validation

for example with this you could write:

use Respect\Validation\Validator;

$eduEmailValidator = Validator::email()->endsWith(".edu");

$eduEmailValidator->validate('waaah');            // false
$eduEmailValidator->validate('[email protected]'); // false
$eduEmailValidator->validate('[email protected]'); // true

This leads to some easy to read code which you'll really appreciate when you come back to this in a few month's time!!

Upvotes: 2

AgA
AgA

Reputation: 2126

function validate_email($email)
{

return preg_match('/[email protected]$/i',$email); //true if success
}

Upvotes: 1

Orsokuma
Orsokuma

Reputation: 622

<?php
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
    exit("Invalid email address");
if(substr($email, -4) !== '.edu')
    exit("Invalid email provider");

It's not the perfect solution, but it'll do what you want it to.
Obviously, change the exit() calls to whatever handling you have

Upvotes: 0

Related Questions