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.
Related
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:
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 new to PHP (not programming overall), and having problems with this simple line of code. I want to check whether some input field has been filled as anysymbolornumber#anysymbolornumber just for checking whether correct email was typed. I don't get any error, but the whole check system doesn't work. Here is my code and thanks!
if ($email = "[a-zA-Z0-9]#[a-zA-Z0-9]")
{
Since your new to php , i suggest you should buy a book or read an tutorial or two.
For email validation you should use filter_var an build in function that comes with with php 5.2 and up :
<?php
if(!filter_var("someone#example....com", FILTER_VALIDATE_EMAIL)){
echo("E-mail is not valid");
}else{
echo("E-mail is valid");
}
?>
you can use other functions .. instead of regular expressions
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}else{
echo "Not a valid email";
}
As correctly pointed out in the comments, the regex you are using isn't actually a very good way of validating the email. There are much better ways, but if you are just wanting to get a look at how regular expressions work, it is a starting point. I am not an expert in regex, but this will at least get your if statement working :)
if(preg_match("[a-zA-Z0-9]#[a-zA-Z0-9]",$email)
{
// Your stuff
}
It looks like you're trying to verify that an email address matches a certain pattern. But you're not using the proper function. You probably want something like preg_match( $pattern, $target ).
Also, your regex isn't doing what you would want anyway. In particular, you need some quantifiers, or else your email addresses will only be able to consist of one character ahead of the #, and one after. And you need anchors at the beginning and end of the sequence so that you're matching against the entire address, not just the two characters closest to the #.
Consider this:
if( preg_match("^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+$", $email ) ) {
// Whatever
}
Keep in mind, however, that this is really a poor-man's approach to validating an email address. Email addresses can contain a lot more characters than those listed in the character class I provided. Furthermore, it would also be possible to construct an invalid email address with those same character classes. It doesn't even begin to deal with Unicode. Using a regex to validate an email address is quite difficult. Friedl takes a shot at it in Mastering Regular Expressions (O'Reilly), and his effort takes a 2KB regular expression pattern. At best, this is only a basic sanity check. It's not a secure means of verifying an email address. At worst, it literally misses valid regexes, and still matches invalid ones.
There is the mailparse_rfc822_parse_addresses function which is more reliable in detecting and matching email addresses.
You need to use preg_match to run the regular expression.
Now you're setting the $email = to the regular expression.
It could look like:
if ( preg_match("[a-zA-Z0-9]#[a-zA-Z0-9]", $email ))
Also keep in mind when matching in an if you must use the == operator.
I believe best pratice would be to use a filter_var instead like:
if( ! filter_var( $email , FILTER_VALIDATE_EMAIL )) {
// Failed.
}
Another way taken from: http://www.linuxjournal.com/article/9585
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!ereg("^[^#]{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
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$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
(!ereg("^(([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;
}
I use the filter_var PHP function to validate email address when a user signs up to my site.
I use this code from the post:
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
then later I do:
if(!$email) {
// return to the form
}
else {
// send registration info
}
now when I var_dump($email), I get the output:
string(23) "user."name"#example.com"
I would like to know why this does not return false. I think the double quotes are not acceptable, so why does PHP say it’s valid?
It is a valid email address :
A quoted string may exist as a dot separated entity within the
local-part or it may exist when the outermost quotes are the outermost
chars of the local-part (e.g. abc."defghi".xyz#example.com or
"abcdefghixyz"#example.com are allowed. abc"defghi"xyz#example.com is
not; neither is abc\"def\"ghi#example.com).
I had the same problem (see Dalmas on why it's valid) and here's how I fixed it:
filter_var($email, FILTER_SANITIZE_EMAIL);
eg:
$email = 'user."name"#example.com';
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
will output:
string(21) "user.name#example.com"
Then you can validate the email using your validation.
you can get more information on the php site