How to place my email validation script into a php function - php

Struggling to create a function to validate any email address using the script below
if (!preg_match('/^(?=^.{6,64}$)[a-zA-Z0-9][a-zA-Z0-9\._\-&!?=#]*#/', $user_mail)) {
$error_mail = empty_mail;
$display_form = TRUE;
$validation_error = TRUE;
} else {
$domain = preg_replace('/^[a-zA-Z0-9][a-zA-Z0-9\._\-&!?=#]*#/', '', $user_mail);
if (!checkdnsrr($domain)) {
$error_mail = empty_mail;
$display_form = TRUE;
$validation_error = TRUE;
}
}

Server-side validation:
It is a good idea to always validate data server-side.
Of course you need to do this client site with JavaScript but you can never trust client validation because you can easily pass that.
That said, hereby the simple PHP server-side e-mail address validation:
//Will return a boolean
filter_var('bob#example.com', FILTER_VALIDATE_EMAIL);
Documentation:
http://php.net/manual/en/function.filter-var.php

Define the function and call the function with parameters like this
<?php
function validate_email($user_mail)
{
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
if (preg_match($pattern, $user_mail)) {
return "valid email format";
}
else
{
return "Invalid email format";
}
}
echo validate_email('jothi007##gmail.com');
?>
OUTPUT :
valid email format

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.

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
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('waaah#domain.com'); // false
$eduEmailValidator->validate('waaah#domain.edu'); // 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!!
function validate_email($email)
{
return preg_match('/.+#ucla.edu$/i',$email); //true if success
}
<?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
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
}
}

Domain specific email validation

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.

PHP: Check does email contains "#" and "."

Im new in php and this should be a easy to make, but I dont now how.
I want to check does $address has characters "#" and "."
<?php
function testEmail($address){
$a = strpos("/#/", $address);
$b = strpos("/./", $address);
if (($a != false) && ($b != false)) {
echo "Email is OK";
} else {
echo "Email is NOT OK";
}
}
testEmail("testmail#gmail.com");
?>
You can simply use filter_var to check validity of email.
$email = 'gaurang#gmail.com'
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Email correct
}
else {
//Email not correct
}
Is your question about this specific piece of code? Then #wroniasty's answer is correct.
But you really don't want to use a regex to test email validity, unless you want to use monstrosities like these.
However, if your question really is "How can I validate an email address?", then take a look at filter_var().
You can pass it the filter FILTER_VALIDATE_EMAIL, so it will validate the email address catching quite a bit of edge cases.
You can check an address using the following code:
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// valid email
} else {
// invalid email
}
<?php
function testEmail($address) {
if (preg_match ( "/\.|#/", $address))
echo "Email OK";
else
echo "Email not OK";
}
?>
a better way to check for valid email address:
<?
function isValidEmail($email){
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
?>

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');
?>

Categories