This question already has answers here:
How to validate an Email in PHP?
(7 answers)
Closed 6 years ago.
I have this code that checks if an email is valid:
$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.";
}
assuming that I have the following string below:
<html>
<body>
<p>abc123#sdsd.com</p>
</body>
</html>
How could I check if that string has an email or not? (since it does not work with the above code)
The ^ and $ are anchors, requiring the full string match. If you take that off it will match an email somewhere in the string.
Regex Demo: https://regex101.com/r/xI0bC2/1
PHP Usage (with updated to store found email):
<?php
$email = "<html>
<body>
<p>abc123#sdsd.com</p>
</body>
</html>";
$regex = '/[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/';
if (preg_match($regex, $email, $email_is)) {
echo $email_is[0] . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
PHP Demo: https://eval.in/618679
There isn't real solution to this problem, since you will easily obtain false positive.
First thing, your pattern is too naive and doesn't match many email addresses that are correct. However a pattern that matches all email addresses doesn't really exist (or is too complicated and inefficient).
A compromise is to select all text nodes that contains a # using XPath. Then you split each text node on white-spaces and you test each part with the build-in email validation PHP function: filter_var ($part, FILTER_VALIDATE_EMAIL)
Related
This question already has answers here:
Email validation using regular expression in PHP
(11 answers)
Closed 3 years ago.
Everybody, I need To allow just string and numbers and dots "." in my email
'email' => 'required|string|email|unique:users|not_regex:/^.+$/i|regex :/^.+#.+$/i',
My Code Here is not allowing for "." i ned to allow just "." and block others like
[# / \ $%^&* etc]
You actually don't need a regex nowadays to validate a string consisting of an email address that should only include letters, numbers, and the # and dot symbols. PHP allows for proper validation when you apply filter_var() twice, first to sanitize the data and then again to validate it, as follows:
<?php
// Variables to check
$emailA = "john1.doe#example.com";
$emailB = "john1.doe#example#.com";
// Remove all illegal characters from email
$emailValid = filter_var($emailA, FILTER_SANITIZE_EMAIL);
$emailInvalid = filter_var($emailB, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (filter_var($emailValid, FILTER_VALIDATE_EMAIL)) {
echo("$emailValid is a valid email address"),"\n";
} else {
echo("$emailValid is not a valid email address");
}
if (filter_var($emailInvalid, FILTER_VALIDATE_EMAIL)) {
echo("$emailInvalid is a valid email address");
} else {
echo("$emailInvalid is not a valid email address");
}
See live code
Note, if this code seems familiar, I admit that I modified the example given here :)
However if you insist on using a regex, here is one way to do so:
<?php
$emailA = "john1#here.com";
$emailB = "john1#here#.com";
function validateEmail( $email ){
$regex = "/^[a-zA-Z0-9.]+#[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}/";
$error = "\nOnly letters, numbers, dot and # are allowed";
echo (preg_match($regex,$email))? "$email is valid\n" : "$error - $email is invalid\n";
return true;
}
validateEmail( $emailA );
validateEmail( $emailB );
See live code
It might seem kind of odd to have validateEmail() return true whether an email is valid or invalid. The return value can be useful if you need to verify that this function actually executed; see example here.
I am a regex noob but I wish to write a regex to check for email for domain name xyz.com.it if user key in abc.com or other TLD domain names, it will pass. If user keys in xyz after the # then, only xyz.com.it will pass, others like xyz.net.it or xyz.net will not pass.Any idea how to do it?
I had tried
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var regexEmail = regex.test($('#email').val());
that only validates normal email
Now instead of using regex you can simply use strstr function of PHP like as
$email = "xyz#xyz.com";
$email2 = "xyz#xyz.net";
$valid_domain = "#xyz.com";
function checkValidDomain($email, $valid_domain){
if(!filter_var($email,FILTER_VALIDATE_EMAIL) !== false){
if(strstr($email,"#") == $valid_domain){
return "Valid";
}else{
return "Invalid";
}
}else{
return "Invalid Email";
}
}
echo checkValidDomain($email, $valid_domain);// Valid
echo checkValidDomain($email2, $valid_domain);// Invalid
Why I didn't used regex over here you can read many of those threads on SO too Email validation using regular expression in PHP and Using a regular expression to validate an email address
This question already has answers here:
How can I validate an email address using a regular expression?
(79 answers)
Closed 7 years ago.
function validateemail($email) {
$v = "/[a-zA-Z0-9_-.+]+#[a-zA-Z0-9-]+.[a-zA-Z]+/";
return (bool)preg_match($v, $email);
}
// check e-mail address, to see if it's a valid phone number
if ($validateemail($email)) {
$error = true;
echo 'Invalid phone number!';
}
I'm trying to check if an e-mail address is valid by the function validateemail, if it's an invalid phone number a message is displayed and $error is set to true. However I can't seem to get this code to work, there are no syntax errors as far as I know. Any advice would be appreciated.
BTW - I know there are other ways to validate e-mail addresses, this is for a college project and for that purpose we have to use regex.
Thanks in advance!
You have - not in the final position inside the first [a-zA-Z0-9_-.+] group.
Try
[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+.[a-zA-Z]+
Have a look at this example.
You need to escape the dash as it can also be used to indicate a character range.
function validateemail($email) {
$v = "/[a-zA-Z0-9_\-.+]+#[a-zA-Z0-9-]+.[a-zA-Z]+/";
return (bool)preg_match($v, $email);
}
If you only want to check if it is a valide e-mail or not, I'd suggest filter_var($email, FILTER_VALIDATE_EMAIL, e.g.:
<?php
$email = "john.doe#example.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");
}
?>
Source: www.w3schools.com/php/filter_validate_email.asp
i am trying to find the common errors users have while entering email ids. I can always validate EMAIL using PHP Email Filter
$email = "someone#exa mple.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "E-mail is valid";
}
or pattern matching
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
I agree that these are not full proof ways to validate emails. However they should capture 80% of cases.
What I want is - Which position email became invalid? if its a space, at what position user had entered space. or did it fail because of "." in the end?
Any pointers?
-Ajay
PS : I have seen other thread regarding email validations. I can add complexity and make it 100%. concern here is to capture the most common mistakes made by people when entering Email ID.
This is difficult because sometimes it's not always a single character that makes an email address invalid. The example you give could easily be solved by:
$position = strpos('someone#exa mple.com', ' ');
However, it seems you are not interested in an all encompassing solution but rather something that will catch the majority of character based errors. I would take the approach of using the regular expression but capture each section of the email address in a sub pattern for further validation. For example:
$matches = null;
$result = preg_match("/(([\w\-]+)\#([\w\-]+)\.([\w\-]+))/", $email, $matches);
var_dump($matches);
By capturing sections of the regex validation in sub patterns you could then dive further into each section and run similar or different tests to determine where the user went wrong. For example you could try and match up the TLD of the email address against a whitelist. Of course there are also much more robust email validators in frameworks like Zend or Symfony that will tell you more specifically WHY an email address is not valid, but in terms of knowing which specific character position is at fault (assuming it's a character that is at fault) I think a combination of tactics would work best.
There is no way I know of in Java to report back the point at which a regex failed. What you could do is start building a set of common errors (as described by Manu) that you can check for (this might or might not use regex expressions). Then categorize into these known errors and 'other', counting the frequency of each. When an 'other' error occurs, develop a regex that would catch it.
If you want some assistance with tracking down why the regex failed you could use a utility such as regexbuddy, shown in this answer.
Just implement some checks on your own:
Point at the end:
if(substr($email, -1) == '.')
echo "Please remove the point at the end of you email";
Spaces found:
$spacePos = strpos($email, ' ');
if(spacePos !== false)
echo "Please remove the space at pos: ".$spacePos;
And so on...
First of all, I would like to say that the reason your example fails is not the space. It is the lack of '.' in former part and lack of '#' in the latter part.
If you input
'someone#example.co m' or 's omeone#example.com', it will success.
So you may need 'begin with' and 'end with' pattern to check strictly.
There is no exist method to check where a regular expression match fails as I know since check only gives the matches, but if you really want to find it out , we can do something by 'break down' the regular expression.
Let's take a look at your example check.
preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",'someone#example.com.');
If it fails, you can check where its 'sub expression' successes and find out where the problem is:
$email = "someone#example.com.";
if(!preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",$email)){ // fails because the final '.'
if(preg_match("/^[\w\-]+\#[\w\-]+\./",$email,$matches)){ // successes
$un_match = "[\w\-]+"; // What is taken from the tail of the regular expression.
foreach ($matches as $match){
$email_tail = str_replace($match,'',$email); // The email without the matching part. in this case : 'com.'
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){ // Check and delete the part that tail match the sub expression. In this example, 'com' matches /[\w\-]+/ but '.' doesn't.
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
}
}
}
var_dump($result); // you will get the last '.'
IF you understand the upper example, then we can make our solution more common, for instance, something like below:
$email = 'som eone#example.com.';
$pattern_chips = array(
'/^[\w\-]+\#[\w\-]+\./' => '[\w\-]+',
'/^[\w\-]+\#[\w\-]+/' => '\.',
'/^[\w\-]+\#/' => '[\w\-]+',
'/^[\w\-]+/' => '\#',
);
if(!preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",$email)){
$result = $email;
foreach ($pattern_chips as $pattern => $un_match){
if(preg_match($pattern,$email,$matches)){
$email_tail = str_replace($matches[0],'',$email);
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
break;
}
}
if(empty($result)){
echo "There has to be something more follows {$email}";
}else{
var_dump($result);
}
}else{
echo "success";
}
and you will get output:
string ' eone#example.com.' (length=18)
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is there a php library for email address validation?
How can I create a validation for email address?
use filter
<?php
$email_a = 'joe#example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This (email_b) email address is considered valid.";
}
?>
If you're looking for full control, you can test the email against a regular expression of your own requirements. You can accomplish this using PHP's preg_match() method.
Example:
<?php
echo preg_match('/^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+$/', 'bob#example.com');
?>
If the email address is valid, preg_match will return 1. Otherwise, preg_match will return a value of 0.
-OR-
Use PHP's built in filter:
<?php
echo filter_var('bob#example.com', FILTER_VALIDATE_EMAIL);
?>
Of'course, I've seen many people state that FILTER_VALIDATE_EMAIL is not enough, and return to regular expressions.
You can learn more about PHP regular expressions here:
http://php.net/manual/en/book.regex.php