I am pretty much new with regular expression. I am developing a project in PHP and i need to validate email address. After searching in this site and google i found the fol
You should use the function filter_vars()
to validate your input instead of your own regexp.
Example:
filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)
More info in the documentation : http://php.net/manual/en/function.filter-var.php
it looks like you don't really need that bigger code to just validate a email.
<?php
$email = "abc123@sdsd.com";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
?>
Try this one and let me know
There more than one ways to check if an e-mail is valid.
One simple way is to use this function:
function validate($email) {
return preg_match("/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/", $email);
}
It is from a code snippet found here: Basic Email Validation in PHP
Although this implementation would work most of the time it may allow some wrong emails. The following implementation ahould be 100% accurate but is also quite complex:
function validate($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex + 1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen - 1] == '.') {
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))) {
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) {
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain ,"A"))) {
$isValid = false;
}
}
return $isValid;
}
This code is from snippet found here: Strict Email Validation in PHP
Hope this helps!
I got here looking for a solution and the answer presented by Wayne Whitty do the job, indeed.
BTW, I think it is good to mention that filter_var
function is not RFC5321 compliant. Altought the docs does not say it is, some RFC5321 valid email address will be flagged as invalid by this function, like:
As presented by this comment http://php.net/manual/pt_BR/function.filter-var.php#112492
try this regx it would work fine
/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
or php filter filter_var
filter_var($email, FILTER_VALIDATE_EMAIL)
like
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//yup its valid email
}
Remove the iD
at the end of the regex