5

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

Derek Lim
  • 321
  • 1
  • 3
  • 14

1 Answers1

0

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

Community
  • 1
  • 1
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • @uchida thanks,I am using JQuery though. Your solution is logical but it only deals with part of my problem. I'm looking for validating normal emails too... but thanks anyway – Derek Lim Apr 18 '16 at 07:01
  • This doesn't take into account valid emailaddresses like `"foo@bar"@example.com` – PeeHaa Apr 18 '16 at 07:13
  • The pattern you have chosen is the broken javascript one. My initial comment also still stands. – PeeHaa Apr 18 '16 at 07:44
  • This will still fail. The point is you cannot simply do a `strstr` because it finds the first occurrence of a character. https://3v4l.org/Kijfh Also `if(!filter_var($email,FILTER_VALIDATE_EMAIL) !== false){` will flag valid emails is incorrect. – PeeHaa Apr 18 '16 at 10:42
  • So what can be the case over here @PeeHaa – Narendrasingh Sisodia Apr 18 '16 at 10:49