Domain specific email validation - php

I am trying to code a registration form where I am validating the email used to sign up.
In a nutshell, I want to ensure that the email ID used to register, is a company domain, and not something like gmail or yahoo.
I have the following code to check IF an email is a part of the given domain, how can I modify this to check that it ISNT in a given list of domains? (eg : gmail.com, yahoo.com,hotmail.com, etc).
return (bool) preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $domain);
Im thinking it should be along these lines, but not entirely sure :
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
EDIT : I tried all the answers given here, the form still submits without a problem no matter what domain I use! (Even a non email seems to work!)
This is how I'm calling the function -
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 8-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
Problem is, no matter what I do, the user gets redirected to the confirmation page (Even with a name made of numbers and an email like "table".

You should do that in a separate step. First check if the e-mailaddress has a valid syntax. Than extract the domain and see if it's not in your blacklist.
function validate($email)
{
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('#', $email, 2);
return !in_array($email_domain, $domains);
}

function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '#' to get the domain
$emailParts = explode('#', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
You'll need a pretty big list of domains.

PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('#',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
Let me know if it's useful.

Related

How do i validate a company email using php preg_match function [duplicate]

I am trying to code a registration form where I am validating the email used to sign up.
In a nutshell, I want to ensure that the email ID used to register, is a company domain, and not something like gmail or yahoo.
I have the following code to check IF an email is a part of the given domain, how can I modify this to check that it ISNT in a given list of domains? (eg : gmail.com, yahoo.com,hotmail.com, etc).
return (bool) preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $domain);
Im thinking it should be along these lines, but not entirely sure :
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
EDIT : I tried all the answers given here, the form still submits without a problem no matter what domain I use! (Even a non email seems to work!)
This is how I'm calling the function -
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 8-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
Problem is, no matter what I do, the user gets redirected to the confirmation page (Even with a name made of numbers and an email like "table".
You should do that in a separate step. First check if the e-mailaddress has a valid syntax. Than extract the domain and see if it's not in your blacklist.
function validate($email)
{
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('#', $email, 2);
return !in_array($email_domain, $domains);
}
function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '#' to get the domain
$emailParts = explode('#', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
You'll need a pretty big list of domains.
PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('#',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
Let me know if it's useful.

Check if the email is belong to student email which contain edu in laravel

I want to check the registered users is student by validating the registered email. I have a table which contain multiple education email domain name such as #mmu.edu.my, #taylor.edu.uk and etc. First the controller should get all available name from database and validate the user email. Then will assign different roles according their university. But the question is how to check the email with each of the available domain name in database.
In my controller i had get the registered user email.
$user_email=$user_info->email;
This is example of the email
alex_9237502834#taylor.edu.uk
Is they any reference for me to learn how to validate?
I'd just cycle through the valid domains as an array, like this:
<?php
$validDomains = array('mmu.edu.my', 'taylor.edu.uk');
function validEmail($email, $validDomains) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$email_parts = explode('#', $email); // [0] will be ben, [1] will be mmu.edu.my
// Valid email address. Does it match anything in our domain whitelist?
foreach($validDomains as $validDomain) {
if (strtolower($validDomain) == $email_parts[1]) {
return true;
}
}
}
return false; // No matches
}
var_dump( validEmail('ben#mmu.edu.my', $validDomains) ); // TRUE
var_dump( validEmail('ben#randomdomain.com', $validDomains) ); // FALSE
var_dump( validEmail('clearlynotanemail', $validDomains) ); // FALSE
var_dump( validEmail('jow#taylor.edu.uk', $validDomains) ); // TRUE
so there are multiple domains i guess? and you need to check the email domain belongs to one of them or not.
so first of all get a query by which you will you will get all the domain.
then
$user_email = explode('#',$entered_email);
$user_email_domain = $user_email[1];
foreach($sql_returned as $sql)
{
if($sql->email == $user_email_domain)
{
do what you want
}
else
{
do something else
}
}
First split the email using "#" sign ..
$user_email=$user_info->email;
$splitted = explode('#',$user_email);
if($splitted[1] == "mmu.edu.my")
{
// attach role here
}
elseif(....)
{
}

Check valid domains in an eMail address

I have the following function that checks whether an eMail is valid:
function validate_email ($getemail, $type)
{
$email = $getemail;
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$chkdomain = explode("#", $email);
$domain = $chkdomain[1];
switch ($type) :
case 1: //FOR USERS
if ($domain == "oxfordmontessori.com" || $domain == "student.com" || $domain == "vendor.com")
return 'Not Valid';
else
return TRUE;
endswitch
;
} else {
return FALSE;
}
}
I am calling function in this way.
var_dump($email);
$response = validate_email($email, '1');
var_dump($response);
if ($response == FALSE) {
$error = "Incorrect Email-Id";
} elseif ($response == 'Not Valid') {
$error = "Email domain is not valid for user.";
}
var_dump($response);
The code has the following issues
Function is that not much restrict with email validation like sunrise#o.com and 'sunrise#o.c' both are consider as valid email id's.
If function return TRUE than also I get "Email domain is not valid for user."
One issue is still their that is on return of TRUE it gives me error Email domain is not valid for user.
its not working because if the domain is set to oxfordmontessori.com student.com or vendor.com, it returns "Not Valid", so #a.com and #b.com will return true. Unless your system is designed to stop people from using those specific domains.
You should probably have either an external variable to store the error, or a pointer in the arguments, rather than returning multiple data types from the function. Either a true or false, maybe an integer, but not a mix of true, false, and string. I think strings (when checked against boolean operators) return true every time.
you can also use html5 email inputs for validation.
Validation is mostly done by regex functions like
preg_match()
Here is an example of using regular expressions for validating email addresses

Best email validation function in general and specific (college domain)?

I know email validation is one of those things which is not the funniest thing on the block. I'm starting up a website and i want to limit my audience to only the people in my college and i also want a preferred email address for my user. So this is a two part question.
Is there a really solid php function out there for email validation?
Can I validate an email from a specific domain. I dont want to just check if the domain exists, because I know www.mycollege.edu exists already. Is there really anyway to validate that the user has a valid #mycollege.edu web address?
This is what I use:
function check_email_address($email) {
// First, we check that there's one # symbol, and that the lengths are right
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
EDIT Replaced depreciated ereg with preg_match for PHP 5.3 compliance
If you really want to make sure its valid make your signup form send them an email with a URL link in that they have to click to validate.
This way not only do you know the address is valid (because the received the email), but you also know the owner of the account has signed up (unless someone else knows his login details).
To make sure it ends correctly you could use explode() on the '#' and check the second part.
$arr = explode('#', $email_address);
if ($arr[1] == 'mycollege.edu')
{
// Then it's from your college
}
PHP also has it's own way of validating email addresses using filter_var: http://www.w3schools.com/php/filter_validate_email.asp
This should work:
if (preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])#mycollege.edu$/', $email)) {
// Valid
}
Read here
http://ru2.php.net/manual/en/book.filter.php
Or in short
var_dump(filter_var('bob#example.com', FILTER_VALIDATE_EMAIL));
this might be a better solution. many answered already, eventhough its little different.
$email = "info#stakoverflow.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo $email ." is a valid email address";
} else {
echo $email ." is not a valid email address";
}
I hope this one has simple to use.
for any e-mail
([a-zA-Z0-9_-]+)(\#)([a-zA-Z0-9_-]+)(\.)([a-zA-Z0-9]{2,4})(\.[a-zA-Z0-9]{2,4})?
for php preg_match function
/([a-zA-Z0-9_-]+)(\#)([a-zA-Z0-9_-]+)(\.)([a-zA-Z0-9]{2,4})(\.[a-zA-Z0-9]{2,4})?/i
for #mycollege.edu
^([a-zA-Z0-9_-]+)(#mycollege.edu)$
for php preg_match function
/^([a-zA-Z0-9_-]+)(#mycollege.edu)$/i
PHP CODE
<?php
$email = 'tahir_aS-adov#mycollege.edu';
preg_match('/^([a-zA-Z0-9_-]+)(#mycollege.edu)$/i', $email, $matches);
if ($matches) {
echo "Matched";
} else {
echo "Not Matched";
}
var_dump($matches);
A simple function using filter_var in php
<?php
function email_validation($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
}
//Test
email_validation('johnson123');
?>

IP Address Validation Help

I am using this IP Validation Function that I came across while browsing, it has been working well until today i ran into a problem.
For some reason the function won't validate this IP as valid: 203.81.192.26
I'm not too great with regular expressions, so would appreciate any help on what could be wrong.
If you have another function, I would appreciate if you could post that for me.
The code for the function is below:
public static function validateIpAddress($ip_addr)
{
global $errors;
$preg = '#^(?:(?: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]?)$#';
if(preg_match($preg, $ip_addr))
{
//now all the intger values are separated
$parts = explode(".", $ip_addr);
//now we need to check each part can range from 0-255
foreach($parts as $ip_parts)
{
if(intval($ip_parts) > 255 || intval($ip_parts) < 0)
{
$errors[] = "ip address is not valid.";
return false;
}
return true;
}
return true;
} else {
$errors[] = "please double check the ip address.";
return false;
}
}
I prefer a simplistic approach described here. This should be considered valid for security purposes. Although make sure you get it from $_SERVER['REMOTE_ADDR'], any other http header can be spoofed.
function validateIpAddress($ip){
return long2ip(ip2long($ip)))==$ip;
}
There is already something built-in to do this : http://fr.php.net/manual/en/filter.examples.validation.php See example 2
<?php
if (filter_var($ip, FILTER_VALIDATE_IP)) {
// Valid
} else {
// Invalid
}
Have you tried using built-in functions to try and validate the address? For example, you can use ip2long and long2ip to convert the human-readable dotted IP address into the number it represents, then back. If the strings are identical, the IP is valid.
There's also the filter extension, which has an IP validation option. filter is included by default in PHP 5.2 and better.
Well, why are you doing both regex and int comparisons? You are "double" checking the address. Also, your second check is not valid, as it will always return true if the first octet is valid (you have a return true inside of the foreach loop).
You could do:
$parts = explode('.', $ip_addr);
if (count($parts) == 4) {
foreach ($parts as $part) {
if ($part > 255 || $part < 0) {
//error
}
}
return true;
} else {
return false;
}
But as others have suggested, ip2long/long2ip may suit your needs better...

Categories