delphiman delphiman - 8 months ago 33
jQuery Question

How to validate email address match with website domain?

I have 2 input fields on my form: email and website

How do I use JQuery to validate the email address domain must matched with the website domain?

For example: if website is or with www or without http:// or without http://www.
Then the email address field must be

Here is my form

$( "#target" ).submit(function( event ) {

var val = $("#website").val();
var myString = val.substr(val.indexOf("http://") + 7);

var emailString = $("#email").val();
var myEmail = emailString.substr(emailString.indexOf("@")+1);

if (myString == myEmail){
$( "span" ).text( "Validated..." ).show();
$( "span" ).text( "Not valid!" ).show();




You can use URL regex by Crockford

Getting only last two parts of domain name is optional, you can use it if you want to convert into This logic will affect domain names like as @samanime points out

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = '';

var result = parse_url.exec(url);

var hostName = result[3];

console.log("host name: ", hostName);

lastTwo = hostName.split('.');
lastTwo = lastTwo.length>2?lastTwo.slice(Math.max(lastTwo.length - 2, 1)) : lastTwo;
onlyMainDomain = lastTwo.join('.');

console.log('only main domain:', onlyMainDomain);

var email = "";

var emailDomain = email.split('@')[1];

console.log('email domain:', emailDomain);

console.log("valid?" , emailDomain === onlyMainDomain);

//check if email domain is a child of hostName

emailDomainRev = emailDomain.split('.').reverse();
hostNameRev = hostName.split('.').reverse();
var emailDomainIsChildOfHostName = true;

if(emailDomainRev.length > hostNameRev.length){
  emailDomainIsChildOfHostName = false;
  emailDomainIsChildOfHostName = emailDomainRev.reduce(function(acc, item, index){
     return acc && (item === hostNameRev[index]);
console.log("email domain is a child of host name:", emailDomainIsChildOfHostName);