Reputation: 37
I am looking to validate e-mail addresses, only allowing e-mails ending with with an @ucla.edu
This is my current function.
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
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
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
Reputation: 2126
function validate_email($email)
{
return preg_match('/[email protected]$/i',$email); //true if success
}
Upvotes: 1
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