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
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 need to validate an input which I will need to later check against a database for its presence in the table. The input either has to be a mobile number (all digits, 10 max len) or an email address. This below is what I did
<?php
$credential = '9999999999';
if (ctype_digit($credential)) {
$mobile_number = $credential;
echo 'Mobile: '. $mobile_number;
} elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
$email = $credential;
echo 'Email: '.$email;
}
output when $credential = '9999999999';
Mobile: 9999999999
output when $credential = 'abc#gmail.com';
Email: abc#gmail.com
Two questions,
Is there a better way of doing it? Like, using preg_match.
The above code manages to differentiate between an email and a mobile number which later I need to match against a database. In a real scenario, the input will be user-supplied, $credential = $_POST['credential']; and then either of two variable will be set accordingly. How do I know which of the two variable is set? If I am to match email to email column or mobile number to the mobile column, I need to know which of the two has value and which one is null.
filter_var($credential, FILTER_VALIDATE_EMAIL) is going to perform better than regex, because that is what it is specifically designed to do.
As for the phone numbers, this seems a little undercooked or too strict. Many people add spaces, parentheses, hyphens, etc without much thought. It will only be irritating to be so strict on the phone number, I think. There are plenty of regex patterns on SO regarding phone number validation. Intimate knowledge of your expected phone number strings are required to answer this confidently. Are you expecting US numbers only? is this international? We don't know, so I can't say what is the best strategy.
This will work:
if (ctype_digit($credential) && strlen($credential)==10) {
$mobile_number = $credential;
echo 'Mobile: '. $mobile_number;
} elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
$email = $credential;
echo 'Email: '.$email;
}
This will also work:
if (preg_match('/^\d{10}$/',$credential)) {
$mobile_number = $credential;
echo 'Mobile: '. $mobile_number;
} elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
$email = $credential;
echo 'Email: '.$email;
}
The speed differences between the two methods will be totally unnoticeable to your users. You should choose whichever approach you prefer personally.
Thank you for answering my first question. For the second part, if you interested, I found this http://php.net/manual/en/function.is-null.php (untested).
This is how you can do it with PHP
if (preg_match('/^\d{10}$/', $string) || filter_var($string, FILTER_VALIDATE_EMAIL)) {
//valid
} else {
//invalid
}
however, you should validate this on client-side as well, to make sure a request is not even sent to the server if the value is invalid.
EDIT:
if (preg_match('/^\d{10}$/', $string)) {
//valid mobile
} else if (filter_var($string, FILTER_VALIDATE_EMAIL)) {
//valid email
} else {
//invalid
}
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)
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:
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