简体   繁体   English

如何验证电子邮件地址与网站域匹配?

[英]How to validate email address match with website domain?

I have 2 input fields on my form: email and website 我在表单上有2个输入字段:电子邮件和网站

How do I use JQuery to validate the email address domain must matched with the website domain? 如何使用JQuery验证电子邮件地址域必须与网站域匹配?

For example: if website is http://example.com or with www or without http:// or without http://www . 例如:如果网站是http://example.com或带www或不带http://或不带http:// www Then the email address field must be user@example.com 然后,电子邮件地址字段必须为user@example.com

Here is my form https://jsfiddle.net/zm7e8r7p/ 这是我的表格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();

}

});
});

You can use URL regex by Crockford 您可以使用Crockford的 URL正则表达式

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 . 仅获取域名的最后两个部分是可选的,如果要将ww2.mobile.gmail.com转换为gmail.com ,则可以使用它。 This logic will affect domain names like .co.in as @samanime points out @samanime指出,这种逻辑将影响.co.in等域名

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

Here is a simple JavaScript process to validate email with your domain name. 这是一个简单的JavaScript流程,用于使用您的域名验证电子邮件。

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*/
}

I've added the regular expression Wiktor suggested with a minor change to accept url without protocol. 我添加了Wiktor建议的正则表达式,但进行了较小的更改以接受没有协议的url。

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

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 例如: 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 例如:在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. 看起来不像是一个域,但是如果您拥有顶级域cake ,则可以实现。

So, you can't really trim off the sub-domain and ensure that www.example.com results in an email @example.com . 因此,您无法真正削减子域并确保www.example.com电子邮件@example.com However, you can tell if it's on at least @www.example.com , @example.com or @com , which could all be valid. 但是,您可以判断它是否至少在@www.example.com@example.com@com ,它们都可能是有效的。 (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. 这就是为什么大多数网站要求您单击发送给您的电子邮件中的链接以验证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. 如果有效匹配,则isValidEmail将包含true否则将包含false

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 . 如果您提供的网站无效,则websiteDomain将是undefined Likewise for a completely invalid email, emailDomain will be `undefined. 同样,对于完全无效的电子邮件, emailDomain也将是未定义的。

I update your code. 我更新您的代码。 I give you the link here https://jsfiddle.net/zm7e8r7p/5/ 我在这里给你链接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
      };
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM