delphiman delphiman - 1 month ago 11
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 http://example.com or with www or without http:// or without http://www.
Then the email address field must be user@example.com

Here is my form https://jsfiddle.net/zm7e8r7p/

$(document).ready(function(){
$( "#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();
event.preventDefault();
}else{
$( "span" ).text( "Not valid!" ).show();
event.preventDefault();

}

});
});

Answer

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 ww2.mobile.gmail.com into gmail.com. This logic will affect domain names like .co.in as @samanime points out

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = 'www.mobile.ora.co.in:80/goodparts?q#fragment';

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 = "someone@ora.co.in";

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;
  }
else{
  emailDomainIsChildOfHostName = emailDomainRev.reduce(function(acc, item, index){
     return acc && (item === hostNameRev[index]);
  },true);
  }
console.log("email domain is a child of host name:", emailDomainIsChildOfHostName);