How to validate email address match with website domain?

时间:2016-10-20 19:06:21

标签: javascript jquery regex validation

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();

}

});
});

5 个答案:

答案 0 :(得分:1)

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);

答案 1 :(得分:1)

Here is a simple JavaScript process to validate email with your domain name.

function ValidateEmail(email) {
  var re = /\S+@\S+\.\S+/; /*Regular expression for valid email*/
  return re.test(email);   /*Return `true` if valid, Otherwise return `false`*/
}

var domain = 'www.example@example.com';
var email  ='emaxple@example.com';

if(ValidateEmail(email)){
  email  = email.split('@');                     /* Split email after `@` Sign*/
  email  = email[1]                              /*After split, `email[0]=emaxple, email[1]=emaxple.com`*/
  domain = domain.split('').reverse().join('');  /*Now `domain = moc.elpmaxe@elpmaxe.www`*/
  email  = email.split('').reverse().join('');   /*Now `email = moc.elpmaxe*/
  email  = email + '@';                          /*Now `email = moc.elpmaxe@`*/
  if(domain.indexOf(email)==0){                  /*If only return `0` then valid, Otherwise Invalid*/
    /*Valid with your domain*/
  }else{
    /*Doesn't match with your domain*/
  }
}else{
    /*Invalid Email*/
}

答案 2 :(得分:0)

I've added the regular expression Wiktor suggested with a minor change to accept url without protocol.

Your code would look like this:

$(document).ready(function(){
    $("#target").submit(function(event) {
        var website = $("#website").val();
        var websiteDomain = website.replace(/^(https?:\/\/)?(?:www\.)?/, "");

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

        $("span").text(websiteDomain === emailDomain ? "Valid!" : "Not valid!" ).show()

        event.preventDefault();
    });
});

答案 3 :(得分:0)

There is a tricky part to your question. Technically, you can have a domain with any number of parts. For example: this.is.a.valid.domain.com

With the new custom top-level domains, it can get even trickier, since they make it possible to have all kinds of crazy combinations and lengths. For example: this.is.also.a.valid.name.on.the.top.level.cake

Looks nothing like a domain, but if you owned the top-level domain cake, you could make it happen.

So, you can't really trim off the sub-domain and ensure that www.example.com results in an email @example.com. However, you can tell if it's on at least @www.example.com, @example.com or @com, which could all be valid. (In reality, you couldn't have one on any of the controlled top-level domains, but it's probably good to allow it for those rare cases.)

This is why most websites require you to click a link in an email sent to you to validate your URL.

Using the above criteria I just described, you can do it with this:

var website = "http://www.example.com"; // website from form
var email = "me@example.com"; // email from form
var emailDomain = email.split('@')[1];
var websiteDomain = website.match(/^(?:https?:\/\/)?([^\/]+)/)[1];
var isValidEmail = (websiteDomain || '').lastIndexOf(emailDomain) === (websiteDomain || '').length - (emailDomain || '').length;

isValidEmail will then contain true if it is a valid match, or false if it isn't.

I've added checks for if something fails above so it won't throw an error if one of the above parts are bad. If you're giving an invalid website, websiteDomain will be undefined. Likewise for a completely invalid email, emailDomain will be `undefined.

答案 4 :(得分:0)

I update your code. I give you the link here https://jsfiddle.net/zm7e8r7p/5/

$(document).ready(function(){
      $( "#target" ).submit(function(event) {
      event.preventDefault();
      var emailString = $("#email").val();
      //cut rule by @
      var afterAt = emailString.split('@');

      var val = $("#website").val();
      var myString = val.substr(-(afterAt[1].length));

      console.log(afterAt[1].length);

      if (myString == afterAt[1]){
       console.log('works');return

      }else{
        console.log('not');return
      };
    });
});